python - 如何在Python中忽略几行来运行函数?

标签 python string

我有一个如下所示的文件:

a
b
str1
c
d
str2
e
f

现在我想运行一个 re.sub() 函数,该函数适用于该文件中的行,除了“str1”和“str2”之间的行(即仅适用于行“a”、“b”、“e”和“F”)。我该怎么做?谢谢!

最佳答案

between_strings = False

for line in lines:
    if line == 'str1':
        between_strings = True
    elif line == 'str2':
        between_strings = False
        continue
    if not between_strings:
        re.sub(line)

这是我将如何实现这一点。它会检查每一行,当找到 str1 时,将 Between_strings 设置为 True。当它为 True 时,它​​会跳行。一旦找到 str2,它将再次开始读取行。如果您有任何疑问,请告诉我。

关于python - 如何在Python中忽略几行来运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50612447/

相关文章:

javascript - 如何在javascript中转换数据格式

c++ - C++ 中的 HashMap (int, string[])

PHP strtr 与 str_replace 基准测试

python - 指数曲线拟合不适合

python - 查找列表中多个项目的索引

python - python 中存在多个匹配项时删除两个模式之间的行

php - 如何从用 print_r 打印的数组的输出创建一个数组?

python - 如何将具有字节值的字符串转换回字节?

python - Eratosthenes 筛法速度比较 : Python vs Julia

c++ - 将十六进制字符串转换为cpp中的字符数组