如何在Python中替换字符串中的所有出现的字符串?
字符串是一组字符,可用于表示单个单词或整个短语。在Python中,字符串不需要显式声明,可以带有或不带有说明符来定义,因此它们很容易使用。
Python有各种内置函数和方法来操作和访问字符串。因为Python中的一切都是对象,所以字符串是String类的对象,该类具有几种方法。
在本文中,我们将重点介绍如何在Python中替换字符串中的所有出现的字符串。
阅读更多:Python 教程
使用replace()方法
字符串类的replace()方法接受一个字符串值作为输入,并将修改过的字符串作为输出返回。它有两个必需参数和一个可选参数。以下是此方法的语法。
string.replace(oldvalue, newvalue, count)
其中,
- 旧值 - 您要替换的子字符串。
-
新值 - 表示您要替换的子字符串。
-
计数 - 这是可选参数;它用于指定要替换为新值的旧值的数量。
示例1
在下面的程序中,我们正在获取输入字符串,并使用replace方法将字母“t”替换为“d”。
str1 = "Welcome to tutorialspoint"
print("The given string is")
print(str1)
print("After replacing t with d")
print(str1.replace("t","d"))
输出
上述程序的输出是,
The given string is
Welcome to tutorialspoint
After replacing t with d
Welcome do dudorialspoind
示例2
在下面的程序中,我们正在获取相同的输入字符串,并使用replace()方法将字母“t”替换为“d”,但在此示例中,我们将count参数设置为2。因此,只有2个t出现。
str1 = "Welcome to tutorialspoint"
print("The given string is")
print(str1)
print("After replacing t with d for 2 times")
print(str1.replace("t","d",2))
输出
上述程序的输出是,
The given string is
Welcome to tutorialspoint
After replacing t with d for 2 times
Welcome do dutorialspoint
使用正则表达式
我们也可以使用Python正则表达式将字符串中的所有出现的字符串替换为另一个字符串。Python的re.sub()方法使用新字母替换给定字符串中的现有字母。以下是此方法的语法 –
re.sub(old, new, string);
- Old − 你想要替换的子字符串。
-
New − 你想要替换的新子字符串。
-
String − 源字符串。
示例
在下面的示例中,我们使用re库的子方法将字母“t”替换为“d”。
import re
str1 = "欢迎来到tutorialspoint"
print("给定的字符串是")
print(str1)
print("替换t为d后的字符串是")
print(re.sub("t","d",str1))
输出
以上程序的输出为,
给定的字符串是
欢迎来到tutorialspoint
替换t为d后的字符串是
欢迎daodudorialspoindd
逐个字符遍历
另一种方法是蛮力方法,你需要遍历特定字符串的每个字符并将其与你想要替换的字符进行匹配,如果匹配成功,则替换该字符,否则继续向前移动。
示例
在下面的示例中,我们正在迭代字符串并匹配并替换每个字符。
str1= "欢迎来到tutorialspoint"
new_str = ''
for i in str1:
if(i == 't'):
new_str += 'd'
else:
new_str += i
print("原始字符串是")
print(str1)
print("替换t为d后的字符串是")
print(new_str)
输出
以上程序的输出为,
原始字符串是
欢迎来到tutorialspoint
替换t为d后的字符串是
欢迎daodudorialspoindd