深度阅读

How to remove specific characters from a string in Python

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

To remove specific characters from a string in Python, you can use the str.replace() method or the str.translate() method. Here are some examples:

Using str.replace():

s = "Hello, world!"
s = s.replace(",", "")  # remove commas
print(s)  # "Hello world!"

Using str.translate():

s = "Hello, world!"
s = s.translate(str.maketrans("", "", ","))  # remove commas using translate
print(s)  # "Hello world!"

Both of these methods create a new string object rather than modifying the original string in place, since strings are immutable in Python.

博客作者

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