根据括号计数打印特定字符串

问题描述 投票:-2回答:1
my_stng = " Einstein found out (apple) (fruit) which is (red)(green) in colour"

Requirement:

在上面的字符串中,计算括号出现的次数并多次打印整个字符串。如果括号的数量是3,我需要打印上面的字符串3次。

python python-3.x nlp textblob
1个回答
0
投票

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

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

print(numberOfOccurences * my_stng)

如果你想同时考虑'('和')',你可以将print语句乘以2。

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)

编辑:我看到这个特定帖子的评论链接到其他主题,你提出问题而不提出任何代码或任何尝试的迹象。虽然这在这个网站上很常见,但我建议你学习如何编码,你需要弄清楚。你必须尝试失败,直到你真正开始建立知识。

© www.soinside.com 2019 - 2024. All rights reserved.