Python string replace() function is used to create a string by replacing some parts of another string.
Python字符串replace()函数用于通过替换另一个string的某些部分来创建字符串 。
Python字符串替换 (Python String replace)
Python String replace() function syntax is:
Python字符串replace()函数语法为:
str.replace(old, new[, count])
The original string remains unmodified. The new string is a copy of the original string with all occurrences of substring old replaced by new.
原始字符串保持不变。 新字符串是原始字符串的副本,所有出现的旧子字符串都由new替换。
If optional argument count
is provided, then only first count occurrences are replaced.
如果提供了可选的参数count
,则仅替换第一个计数出现的位置。
We can use this function to replace characters in a string too.
我们也可以使用此功能替换字符串中的字符。
Python字符串replace()示例 (Python String replace() example)
Let’s look at some simple examples of using string replace() function.
让我们看一些使用字符串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)
Output:
输出:
Python is Nice
cococo
Python字符串替换为计数 (Python string replace with count)
s = 'dododo'
str_new = s.replace('d', 'c', 2)
print(str_new)
Output: cocodo
输出: cocodo
用户输入的字符串replace()示例 (String replace() example with user input)
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)
Output:
输出:
Please provide input data
a,e,i,o,u
Please provide current delimiter
,
Please provide new delimiter
:
Updated Data = a:e:i:o:u
We can also use str.replace() function as shown below.
我们还可以使用str.replace()函数,如下所示。
print(str.replace('abca', 'a', 'A'))
Output: AbcA
输出: AbcA
Reference: API Doc
参考: API文档