根据出现括号的次数打印特定字符串

print a particular string based on the count of parenthesis occurs

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

要求:

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.

如果你确定每个'('都有一对')'并且你想通过一对括号打印,你可以这样做:

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

print(numberOfOccurences * my_stng)

如果您想同时考虑“(”和“)”,您可以将 print 语句乘以二。

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

print(2 * numberOfOccurences * my_stng)

最后,如果您不确定每对括号是否都已关闭,则必须通过两个字符手动搜索:

numberOfOpenParenthesis = list(my_stng).count('(')
numberOfClosedParenthesis = list(my_stng).count(')')

print((numberOfClosedParenthesis + numberOfOpenParenthesis) * my_stng)

编辑:我看到了对这个特定 post 的评论,该评论链接到其他主题,您可以在其中提出问题而无需提供任何代码或任何尝试的迹象。虽然这在本网站中很常见,但我建议您要学习如何编码,您需要亲自动手。你必须尝试失败,直到你真正开始积累知识。