python - 忽略python中字符串的特定部分

标签 python python-3.x

我的字符串是

I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny

所以我不想替换“Destiny”

TAG:{Destiny2,the last Destiny game}     

但我想用

替换最后一个词“命运”
TAG:{Destiny:Destiny}    

我总是想在替换时忽略 TAG 中的字符串。

预期输出:

I liked TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny:Destiny}

请帮忙。

最佳答案

您需要首先解析字符串,找出哪些 Destiny 子字符串位于标记内,哪些不在标记内。我在下面使用 re.split 完成了此操作.

我使用 re.split 返回围绕正则表达式模式 TAG:?{.*?} 的子字符串列表,并且因为我将模式括在括号中,所以标签包含在列表中以及。在使用 re.split 时,非标签将始终具有偶数索引,而标签将始终具有奇数索引。因此,我检查索引是否为偶数,如果是偶数,则将 Destiny 替换为 TAG:{Destiny,Destiny}

import re

s = 'TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is Destiny'
result = []
for i, substring in enumerate(re.split('(TAG:?{.*?})', s)):
    if i % 2 == 0:
        substring = substring.replace('Destiny', 'TAG:{Destiny,Destiny}')
    result.append(substring)
result = ''.join(result)
print(result) # TAG:{Destiny2,the last Destiny game}, now I play TAG{Fortnite,Fortnite} is TAG:{Destiny,Destiny}

只要您没有将标签嵌套在其他标签内,此方法就可以工作。

关于python - 忽略python中字符串的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50145412/

相关文章:

python - 线程代码在调用 FFI 进程时崩溃

python - 使用 MongoEngine 指定集合名称

python - Django 错误中关于 Page 的顶级信息

python - 在keras中的自定义损失函数中做一些数学计算

python - 如何在QLCD数字屏上显示多个数字?

Python3 super() 和泛型类

python - 将输入传递给 shell 脚本调用的 python 脚本

python - 使用 loc 替换/选择列中的值。 Pandas

python - 按特定顺序枚举篮子中的球

python-3.x - Sklearn - 线性回归