Python字符串replace()

Python字符串replace()

Python字符串replace()

Python字符串replace()

  Python 字符串方法replace()返回字符串的副本,其中old的出现已被替换为new,可选地将替换次数限制为count。本文晓得博客为你介绍Python字符串replace()。

replace()语法

  以下是replace()方法的语法 –

string.replace(old, new, count)

  参数

  • old – 这是要替换的旧子字符串。
  • new – 这是新的子字符串,它将替换旧的子字符串。
  • count – 如果给出此可选参数 ,则仅替换第一次出现的计数。(新字符串替换旧字符串的个数)

  注意如果count未指定,该replace()方法将替换所有出现的旧字符串与新字符串

  推荐:Python中json.load()和json.loads()之间的区别

replace()返回值

  此方法返回字符串的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 max,则仅替换第一个 count 出现。该replace()方法返回字符串的副本,其中老的子字符串替换为新的子串。原字符串不变。

replace()返回值

  如果老的未找到子字符串,它返回原始字符串的副本

song = 'cold, cold heart'

# replacing 'cold' with 'hurt'
print(song.replace('cold', 'hurt'))

song = 'Let it be, let it be, let it be, let it be'

# replacing only two occurences of 'let'
print(song.replace('let', "don't let", 2))

  如果老的未找到子字符串,它返回原始字符串的副本。

hurt, hurt heart
Let it be, don't let it be, don't let it be, let it be

  推荐:如何用Python中将Base64字符串转换为图像

replace()示例

Python字符串replace示例
song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')

# The original string is unchanged
print('Original string:', song)

print('Replaced string:', replaced_song)

song = 'let it be, let it be, let it be'

# maximum of 0 substring is replaced
# returns copy of the original string
print(song.replace('let', 'so', 0))

  输出:

Original string: cold, cold heart
Replaced string: celd, celd heart
let it be, let it be, let it be

总结

  以上是晓得博客为你介绍的Python字符串replace(),希望对你学习python有帮助,如您是新手,也可参考零基础如何开始学习Python

  推荐:Python 3 教程

给文章评分

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Python字符串replace()

转载请保留链接:https://www.pythonthree.com/python-string-replace/

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部