我正在或尝试使用 Python 3 编写代码,它接受一串大括号,例如 '{{]]' 并查找相邻的一对大括号,即 '[' 紧接着 '] ',或 '{' 紧跟 '}',或 '(' 紧接着 ')'。它返回它找到的第一对,如果没有找到则返回 False。为此,我写了一些代码:
# write a function that scans a sequence of braces to find a "married pair", or else returns false if there is none.
def find(mystring):
for x in mystring[0:-1]:
y=mystring[mystring.index(x)+1:][0]
if (x == '[' and y == ']') or (x == '{' and y == '}') or (x == '(' and y == ')'):
return x,y
else:
continue
return False
好吧,当我在字符串 ({})
上尝试查找函数时,它起作用了。它按预期返回 ('{','}')
。但是当我尝试查找 ('{{}}')
时,它意外地返回了 False
。运行 ([()])
意外返回 False
。 ([{}])
按预期返回 True
。
这是怎么回事?
最佳答案
mystring.index(x)
不会返回您正在查看的索引。它返回给定字符的 first 索引。因此,当您位于 {{}}
的第二个 {
字符时,index(x)
返回 0。如果您使用索引迭代时,使用 enumerate
.
固定版本可能是这样的:
def find(mystring):
for i,x in enumerate(mystring[:-1]):
y = mystring[i+1]
if (x == '[' and y == ']') or (x == '{' and y == '}') or (x == '(' and y == ')'):
return x,y
return False
关于python - Python 3 中字符串函数的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56973030/