python - Python 3 中字符串函数的意外输出

标签 python python-3.x jupyter-notebook

我正在或尝试使用 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/

相关文章:

jupyter-notebook - 获取jupyter服务器根目录的方法

python - "ImportError: No module named"错误似乎与我的代码无关

python - 为什么我不能连接此列表中的项目但我可以将它们相乘?

python - 与 MySQL 通信时,我的 Python 脚本没有错误,仍然没有变化

python - 从 DataFrame 的最后一行获取列表

python-3.x - 如何在 Python 的列表中找到 "nearest neighbors"?

python - 文本文件中的Scrapy start_urls

python - 多个文件中的单词匹配

python - Jupyter Notebook 和 matplotlib(运行时警告): continue to display plots after closing

python - 是什么让这两个具有不同缩进的Python代码产生不同的结果