如何在Python中替换字符串中的字符

185 阅读3分钟

在我们的程序中处理文本数据时,有时我们可能需要修改数据。在这篇文章中,我们将研究在Python中替换字符串中的字符的各种方法。我们将讨论各种用例,以更好地理解这个过程。

如何替换字符串中的一个字符?

为了用另一个字符替换字符串中的一个字符,我们可以使用 replace() 方法。replace()方法在字符串上调用时,将被替换的字符作为第一个输入,将新字符作为第二个输入,将被替换的字符数作为一个可选输入。replace()方法的语法如下。

str.replace(old_character, new_character, n)

这里,old_character是将被替换成new_character的字符。输入n是可选的参数,指定要用new_character替换的old_character的出现次数。

现在让我们来讨论一下如何使用各种使用情况来替换字符串中的字符。

替换字符串中所有出现的字符

要用一个新的字符替换所有出现的字符,我们只需在对字符串调用replace()方法时,将旧的字符和新的字符作为输入传给它。你可以在下面的例子中观察到这一点。

input_string = "This is PythonForBeginners.com. Here, you   can read python tutorials for free."
new_string = input_string.replace('i', "I")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)

输出。

The original string is:
This is PythonForBeginners.com. Here, you   can read python tutorials for free.
Output String is:
ThIs Is PythonForBegInners.com. Here, you   can read python tutorIals for free.

在这里,我们使用replace()方法将所有出现的字符'i'替换成了字符'I'。

我们还可以用一组新的字符来替换一组连续的字符,而不是替换单个字符。替换连续字符组的语法没有变化。我们只需将旧的字符和新的字符传递给replace()方法,如下所示。

input_string = "This is PythonForBeginners.com. Here, you   can read python tutorials for free."
new_string = input_string.replace('is', "IS")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)

输出。

The original string is:
This is PythonForBeginners.com. Here, you   can read python tutorials for free.
Output String is:
ThIS IS PythonForBeginners.com. Here, you   can read python tutorials for free.

在这个例子中,你可以看到,我们在输出字符串中用 "IS "替换了 "is"。

替换字符串中前n个出现的字符

要用另一个字符替换一个字符串中的前n个出现的字符,我们可以在replace()方法中指定可选的输入参数。在指定了要替换的字符的出现次数后,从字符串开始的n个出现的字符将被替换。

例如,我们可以用 "A "替换给定文本中出现的前3个字符 "a",如下所示。

input_string = "An owl sat on the back of an elephant and started to tease him."
new_string = input_string.replace('a', "A",3)
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)

输出。

The original string is:
An owl sat on the back of an elephant and started to tease him.
Output String is:
An owl sAt on the bAck of An elephant and started to tease him.

使用replace()方法的好处

一般来说,我们需要使用正则表达式来寻找字符串中的字符来替换它们。正则表达式很难理解,需要谨慎使用,以正确匹配要替换的字符。此外,使用正则表达式在计算上也是低效的。因此,replace()方法为我们提供了一种简单且计算效率高的方法来替换字符串中的字符。

总结

在这篇文章中,我们讨论了 Python 中的 replace() 方法。