Search code examples
pythonpython-3.xnlptextblob

print a particular string based on the count of parenthesis occurs


my_stng = " Einstein found out (apple) (fruit) which is (red)(green) in colour"

Requirement:

in the above string, count the number of times the parenthesis occurs and print the whole string that many times. if the count of parenthesis is 3, i need to print the above string 3 times.


Solution

  • if you have sure every '(' has is pair ')' and you want to print by pair of parentheses, you could do:

    numberOfOccurences = list(my_stng).count('(')
    
    print(numberOfOccurences * my_stng)
    

    if you want to take into consideration both '(' and ')', you can multiply the print statement by two.

    numberOfOccurences = list(my_stng).count('(')
    
    print(2 * numberOfOccurences * my_stng)
    

    Finally, if you are not sure that every pair of parenthesis is closed you have to search manually by both characters:

    numberOfOpenParenthesis = list(my_stng).count('(')
    numberOfClosedParenthesis = list(my_stng).count(')')
    
    print((numberOfClosedParenthesis + numberOfOpenParenthesis) * my_stng)
    

    EDIT: I saw a comment to this particular post that linked to other topics where you ask for questions without presenting any code or any sign of trying. While this is very common in this website, i advised you that for learning how to code, you need to get your hands dirty. You have to try and fail, until you actually start to build knowledge.