繁体   English   中英

替换 Python 中的部分字符串?

[英]Replace part of a string in Python?

我使用正则表达式从 web 页面获取一个字符串,该字符串的一部分可能包含我想用其他内容替换的内容。 怎么可能做到这一点? 我的代码是这样的,例如:

stuff = "Big and small"
if stuff.find(" and ") == -1:
    # make stuff "Big/small"
else:
    stuff = stuff
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

在字符串上使用replace()方法:

>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'

您可以轻松使用.replace() ,如前所述。 但同样重要的是要记住字符串是不可变的。 因此,如果您不将所做的更改分配给变量,那么您将看不到任何更改。 让我解释一下;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

要观察您要应用的更改,您可以分配相同或另一个变量;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM