
从 Python 中的字符串中删除特定字符
问题
要从 Python 中的字符串中删除特定字符,常见的方法有:方法是循环遍历字符串,识别并删除不需要的字符。然而,这种方法的实现通常无法修改字符串。
答案
理解 Python 中字符串的不变性至关重要。字符串是不可变的,这意味着它们不能直接修改。任何更改字符串中字符的尝试都会导致创建新字符串。
要正确删除特定字符,请将修改后的字符串分配回原始变量。下面是一个示例:
1 2 3 4 5 | line = "Hello, world!"
for char in " ?.!/;:" :
line = line.replace(char, "" ) # Create a new string with the character removed
print (line) # Output: "Hello,world"
|
登录后复制
或者,您可以使用内置的 str.translate 函数:
1 2 3 4 | line = "Hello, world!"
line = line.translate(None, "!@#$" ) # Remove characters from "!@#$"
print (line) # Output: "Hello, world"
|
登录后复制
或者使用 re.sub 进行正则表达式替换:
1 2 3 4 5 | import re
line = "Hello, world!"
line = re.sub( '[!@#$]' , '' , line) # Replace characters in `[]` with an empty string
print (line) # Output: "Hello, world"
|
登录后复制
在Python 3中,对于Unicode字符串:
1 2 3 4 5 | unicode_line = "Hello, world!"
translation_table = {ord(c): None for c in "!@#$" }
unicode_line = unicode_line.translate(translation_table) # Delete characters with None mapping
print (unicode_line) # Output: "Hello, world"
|
登录后复制
通过理解字符串的不变性,您可以在Python中有效地删除特定字符并高效地操作字符串。
以上是如何在Python中高效地删除字符串中的特定字符?的详细内容。更多信息请关注PHP中文网其他相关文章!