Python 如何用另一个字符串替换所有出现的字符串

Python 如何用另一个字符串替换所有出现的字符串

一个字符串是一组字符,用于表示一个单词或整个短语。在Python中,字符串不需要显式声明,并且可以带有或不带有指定器进行定义,因此非常容易使用。

Python具有各种内置函数和方法来操作和访问字符串。因为Python中的所有内容都是对象,所以字符串是String类的一个对象,该类具有几个方法。

本文将重点介绍在Python中用另一个字符串替换所有出现的字符串。

使用replace()方法

字符串类的 replace() 方法接受一个字符串值作为输入,并将修改后的字符串作为输出返回。它有2个必需的参数和1个可选的参数。以下是该方法的语法。

string.replace(oldvalue, newvalue, count)

在下面的程序中,我们输入一个字符串,并使用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的 sub() 方法可以将给定字符串中的现有字母替换为新的字母。以下是该方法的语法:

re.sub(old, new, string);
  • old − 您想要替换的子字符串。

  • new − 您想要替换的新子字符串。

  • string − 源字符串。

示例

在下面给出的示例中,我们使用re库的sub方法将字母“t”替换为“d”。

import re
str1 = "Welcome to tutorialspoint"

print("The given string is")
print(str1)

print("After replacing t with d ")
print(re.sub("t","d",str1))

输出

上述程序的输出是:

The given string is
Welcome to tutorialspoint
After replacing t with d
Welcome do dudorialspoind

遍历每个字符

另一种方法是暴力方法,你遍历特定字符串的每个字符,并将其与要替换的字符进行比较,如果匹配,则替换该字符,否则移动到下一个字符。

示例

在下面的示例中,我们正在迭代字符串并进行匹配和替换。

str1= "Welcome to tutorialspoint"
new_str = ''

for i in str1:
   if(i == 't'):
      new_str += 'd'
   else:
      new_str += i

print("The original string is")
print(str1)

print("The string after replacing t with d ")
print(new_str)

输出

上述程序的输出为:

The original string is
Welcome to tutorialspoint
The string after replacing t with d
Welcome do dudorialspoind

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程