Printing 如何调用python中最深的括号
我试着做这个例子:Printing 如何调用python中最深的括号,printing,Printing,我试着做这个例子: sentence="{My name is {Adam} and I don't work here}" 结果应该是'Adam' 所以我想说的是,不管存在多少个括号,我希望结果显示最后一个闭括号的值,你不能像那样索引字符串。。。最好的方法是使用聪明的正则表达式: >>> import re >>> re.search(r'{[^{}]*}', "{My name is {Adam} and I don't work here}").gro
sentence="{My name is {Adam} and I don't work here}"
结果应该是'Adam'
所以我想说的是,不管存在多少个括号,我希望结果显示最后一个闭括号的值,你不能像那样索引字符串。。。最好的方法是使用聪明的正则表达式:
>>> import re
>>> re.search(r'{[^{}]*}', "{My name is {Adam} and I don't work here}").group()
'{Adam}'
这个正则表达式模式本质上搜索每一组
{}
中没有字符{
或}
。你的问题不清楚,但是如果在任何级别上都只能有一组外括号(即“{My name}{is{Adam}”
和“{My name}is{Adam}”
是无效输入),您可以利用以下事实:您想要的是句子中最后一个大括号
def deepest(sentence):
intermediate = sentence.rpartition("{")[-1]
return intermediate[:intermediate.index("}")]
deepest("{My name is {Adam} and I don't work here}")
# 'Adam'
deepest("{Someone {set us {{up} the bomb}!}}")
# 'up'
regex的答案也做出了这一假设,尽管regex可能会慢得多。如果可以使用多个外大括号,请将问题弄清楚。是否尝试使用
input()
命令替换{adam}?如果尝试查找最里面的括号,可以尝试查看左括号和右括号的数量。您的尝试不会检测任何括号。