Python字符串replace函数注意事项

Python中使用字符串replace函数注意事项

Python的documentation中关于replace函数的介绍如下:

str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

从上文可以看出,替换并不会改变原来字符串的值,替换结果以新字符串的形式返回。

replace()函数用法:

以下实例展示了replace()函数的使用方法::

#以下代码在Python3.5.1下运行通过
original_str='www.baidu.com'
new_str=original_str.replace('baidu','alibaba')
print('original_str=',original_str)
print('new_str=',new_str)
>>> original_str= www.baidu.com
... new_str= www.alibaba.com

结论:从运行结果来看,replace函数确实不会改变原始字符串的值,因为Python 字符串不能被改变,这一点与C字符串不同。
如果需要使用替换后的字符串,需要把它重新赋值给一个新的变量

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值