深度阅读

How to replace characters in a string in Python?

作者
作者
2023年08月22日
更新时间
12.14 分钟
阅读时间
0
阅读量

To replace characters in a string in Python, you can use the replace() method. The replace() method returns a new string where all occurrences of a specified character or substring are replaced with another character or substring.

Here’s an example:

my_string = "Hello, world!"
new_string = my_string.replace(",", ";")
print(new_string)

Output:

"Hello; world!"

In this example, we have defined a string with a comma character. We then call the replace() method on the string to replace the comma character with a semicolon character, and store the result in a new string.

Note that replace() creates a new string, and does not modify the original string. If you want to modify the original string, you can re-assign the result of the replace() method back to the original variable.

You can also replace multiple occurrences of a string or character by chaining the replace() method. For example:

my_string = "Hello, world!"
new_string = my_string.replace(",", "").replace(" ", "")
print(new_string)

Output:

"Helloworld!"

In this example, we have removed both the comma and the space characters from the string by chaining two replace() methods.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。