Python字符串replace()

时间:2020-02-23 14:43:29  来源:igfitidea点击:

Python字符串replace()函数用于通过替换另一个字符串的某些部分来创建字符串。

Python字符串替换

Python字符串replace()函数语法为:

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

原始字符串保持不变。
新字符串是原始字符串的副本,所有出现的子字符串old都被new替换。

如果提供了可选参数count,则仅替换首次出现的计数。

我们也可以使用此功能替换字符串中的字符。

Python String replace()示例

让我们看一些使用字符串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字符串替换为计数

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

输出:cocodo

用户输入的字符串replace()示例

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