Python 字串 replace()

Python 字串 replace() 函式用於建立一個字串,通過替換另一個字串的某些部分來創建它。

Python 字串 replace

Python 字串 replace() 函式的語法是:

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

原始字串保持不變。新字串是原始字串的副本,其中所有子字串old的所有出現都被new替換。如果提供了可選的引數count,那麼只有前count個出現會被替換。我們也可以使用這個函式來替換字串中的字符。

Python 字串 replace() 範例

讓我們看一些使用 string replace() 函式的簡單範例。

s = 'Java is Nice'

# simple string replace example
str_new = s.replace('Java', 'Python')
print(str_new)

# replace character in string
s = 'dododo'
str_new = s.replace('d', 'c')
print(str_new)

輸出:

Python is Nice
cococo

Python string replace with count

s = 'dododo'
str_new = s.replace('d', 'c', 2)
print(str_new)

輸出:cocodo

使用者輸入的字串替換() 範例

input_str = input('Please provide input data\n')
delimiter = input('Please provide current delimiter\n')
delimiter_new = input('Please provide new delimiter\n')
output_str = input_str.replace(delimiter, delimiter_new)
print('Updated Data =', output_str)

輸出:

Please provide input data
a,e,i,o,u
Please provide current delimiter
,
Please provide new delimiter
:
Updated Data = a:e:i:o:u

我們也可以使用 str.replace() 函式,如下所示。

print(str.replace('abca', 'a', 'A'))

輸出:AbcA

您可以從我們的GitHub 存儲庫中查看完整的腳本和更多 Python 字串範例。

參考:API 文件

Source:
https://www.digitalocean.com/community/tutorials/python-string-replace