亚洲区国产区激情区无码区,国产成人mv视频在线观看,国产A毛片AAAAAA,亚洲精品国产首次亮相在线

Python 基礎教程

Python 流程控制

Python 函數

Python 數據類型

Python 文件操作

Python 對象和類

Python 日期和時間

Python 高級知識

Python 參考手冊

Python 字符串 replace() 使用方法及示例

Python 字符串方法

replace()方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數count,則替換不超過 count次。

replace()的語法為:

str.replace(old, new [, count])

replace()參數

replace()方法最多可以使用3個參數:

  • old -您要替換的舊子字符串

  • new -新的子字符串將替換舊的子字符串

  • count(可選)-您要用old子字符串替換子new字符串的次數

如果count 未指定,則replace()方法將所有出現的 old子字符串替換為new子字符串。

replace()返回值

replace()方法返回字符串的副本,其中old子字符串被new子字符串替換。原始字符串不變。

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

示例1:如何使用replace()?

song = 'cold, cold heart'
print (song.replace('cold', 'hurt'))

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

'''只有兩次出現的“ 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

有關String replace()的更多示例

song = 'cold, cold heart'
replaced_song =  song.replace('o', 'e')

# 原始字符串沒有改變
print ('原始字符串:', song)
print ('被替換的字符串:', replaced_song)

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

# 最多替換0個子字符串
# 返回原始字符串的副本
print(song.replace('let', 'so', 0))

運行該程序時,輸出為:

原始字符串: cold, cold heart
被替換的字符串: celd, celd heart
let it be, let it be, let it be

Python 字符串方法