Python 字符串 replace()

Python 字符串替换() 函数用于创建一个字符串,以替换另一个字符串的某些部分(/community/tutorials/python-string)。

Python 字符串替换

Python String 代替() 函数语法是:

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

原始字符串保持不变. 新字符串是原始字符串的副本,所有的子字符串 old 都被替换为 new. 如果提供可选的参数 count,那么只有第一个 count 事件才被替换。

Python String 替换() 示例

让我们来看看一些简单的使用代替( )字符串函数的例子。

 1s = 'Java is Nice'
 2
 3# simple string replace example
 4str_new = s.replace('Java', 'Python')
 5print(str_new)
 6
 7# replace character in string
 8s = 'dododo'
 9str_new = s.replace('d', 'c')
10print(str_new)

输出:

1Python is Nice
2cococo

Python 字符串用 count 取代

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

产品名称: COCODO

用用户输入代替( )字符串示例

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

输出:

1Please provide input data
2a,e,i,o,u
3Please provide current delimiter
4,
5Please provide new delimiter
6:
7Updated Data = a:e:i:o:u

python string replace We can also use str.replace() function as shown below.

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

输出:ABCA

您可以从我们的 GitHub 存储库中查阅完整的脚本和更多 Python String 示例。

引用: API Doc

Published At
Categories with 技术
comments powered by Disqus