Python字符串replace()

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

GitHub Repository. GitHub Repository中检出完整脚本和更多Python String示例。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/23470/python-string-replace

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值