可能重复:
python正则表达式替换匹配字符串的一部分
我使用正则表达式从网页获取字符串,部分字符串可能包含我想用其他东西替换的东西.怎么可能这样做?我的代码是这样的,例如:
stuff = "Big and small"
if stuff.find(" and ") == -1:
# make stuff "Big/small"
else:
stuff = stuff
Run Code Online (Sandbox Code Playgroud)
jam*_*lak 74
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'
Run Code Online (Sandbox Code Playgroud)
Rus*_*ove 21
replace()在字符串上使用该方法:
>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'
Run Code Online (Sandbox Code Playgroud)
.replace()如前所述,您也可以轻松使用。但记住字符串是不可变的也很重要。因此,如果您不将所做的更改分配给变量,那么您将看不到任何更改。让我解释一下;
>>stuff = "bin and small"
>>stuff.replace('and', ',')
>>print(stuff)
"big and small" #no change
Run Code Online (Sandbox Code Playgroud)
要观察要应用的更改,您可以分配相同或另一个变量;
>>stuff = "big and small"
>>stuff = stuff.replace("and", ",")
>>print(stuff)
'big, small'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100856 次 |
| 最近记录: |