Python字符串replace函数注意事项

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zfs2008zfs/article/details/82146286

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字符串不同。
如果需要使用替换后的字符串,需要把它重新赋值给一个新的变量

猜你喜欢

转载自blog.csdn.net/zfs2008zfs/article/details/82146286
今日推荐