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

2024-10-05 10:52:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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.


Tags: oftheinstringismycountout
1条回答
网友
1楼 · 发布于 2024-10-05 10:52:30

如果您确定每个“(”has is pair“)”都有,并且希望用一对括号打印,则可以执行以下操作:

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)

编辑:我看到这篇文章的一条评论,它链接到其他主题,在这里你提问时没有给出任何代码或任何尝试的迹象。虽然这在这个网站上很常见,但我建议你,为了学习如何编码,你需要把手弄脏。你必须尝试失败,直到你真正开始积累知识

相关问题 更多 >

    热门问题