Python – 当字符串与大写和小写字母混合时,有没有办法替换字符串?

扎眼的阳光 python 173

原文标题Python – Is there a way to replace a string when it’s mixed with uppercase and lowercase letters?

如果一个单词中有 d’ 或 ‘s,我想用 d’$ 和 $’s 替换它。

使用word.lower(),检查大写单词是否包含d’和’s就完成了。但是不知道如何用d’$和$’s替换大写字符串。有没有办法改它不使用正则表达式?

x = "D'you d'yeh IT'S she's love"
x = x.split()

b = ["d'", "'s"]
a = ["d'$", "$'s"]
y = x
for b, a in zip(b, a):
    y = [word.replace(b, a) if b in word.lower() else word for word in y]

print(y)

目前的结果如下。

["D'you", "d'$yeh", "IT'S", "she$'s", 'love']

我想要的结果如下。

["D'$you", "d'$yeh", "IT$'S", "she$'s", 'love']

非常感谢您的帮助…

原文链接:https://stackoverflow.com//questions/71910024/python-is-there-a-way-to-replace-a-string-when-its-mixed-with-uppercase-and-l

回复

我来回复
  • Lancelot du Lac的头像
    Lancelot du Lac 评论

    不知道为什么要标记和打印列表,但无论如何都可以:

    x = "D'you d'yeh IT'S she's love"
    
    for a, b in [("D'", "D'$"), ("'S", "$'S"), ("d'", "d'$"), ("'s", "$'s")]:
        x = x.replace(a, b)
    
    print(x.split())
    

    输出:

    ["D'$you", "d'$yeh", "IT$'S", "she$'s", 'love']
    
    2年前 0条评论