python - 在字符串中查找列表元素

标签 python string list

我有一个字符串 'RTKLOANGMSTTTS' 和一个元组列表 [(2,5),(8,9)],它返回一个包含字母 2-5 和 8-9 的字符串,即'TKLOGM'。 我在想类似的事情:

def f(string, lst):
    for element in lst:
        if element in string:
            print string

但是它没有返回任何东西?

最佳答案

试试这个:

def f(source, lst):
    return "".join(source[start - 1:end] for start, end in lst)

这将迭代 lst,在每次迭代时将元组提取到 startend 中。然后它将创建一个新字符串作为 source 字符串的切片,从 start - 1end (我们使用 start - 1 因为你显示 1 表示第一个字符,但是 python 使用 0 索引,所以我们必须减去一个)。最后,我们使用 "".join() 连接所有字符串。

如果您使用不支持生成器语法的旧版本 Python,请改用它:

def f(source, lst):
    return "".join([source[start - 1:end] for start, end in lst])

它的工作原理完全相同,但它没有使用生成器,而是显式地创建了一个被连接的列表。

关于python - 在字符串中查找列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8517072/

相关文章:

python - 尽管 shell 脚本抛出 [Errno 111] 连接被拒绝,但在 Docker 启动时使用 TCP 服务器执行 python3 脚本

python - Plpython 程序中的 Greenplum pandas 数据框集成(来自数据库内部)

c - C 中的字符串反转

c++ - 迭代 std::string 元素

r - 使用 lapply 从数据框列表创建新数据框

python - 如何使 PyQt5 QTreeview 节点在代码中可编辑?

python - 反转字符串中标记的子字符串

python - 将列表列表转换为分隔字符串

python - 基于子列表中的字母数字字符串的列表列表的自然排序?

python - 如何继续openai API响应不完整