处理字符串时常常需要删除一些不需要的字符,比如空格、标点符号、特殊符号等。Python 提供了多种方法来实现这一需求。
使用strip()
strip() 方法是大家日常最常用到的方法,它用于删除字符串开头和结尾的空白字符(包括空格、换行符等)。如果你想删除特定的字符,可以传递一个参数。
original_string = " Hello, World! "
# 删除开头和结尾的空白字符
new_string = original_string.strip()
print(new_string) # 输出: "Hello, World!"
# 删除特定字符
original_string = "***Hello, World!***"
new_string = original_string.strip('*')
print(new_string) # 输出: "Hello, World!"
这个例子中,strip() 方法首先删除了字符串两端的空白字符,然后又删除了字符串两端的星号 *,但是对于字符串中间的空白字符strip()方法就无删除的。
使用str.replace()
对于字符串中间的空白和固定字符,可以使用str.replace()方法来处理。它可以删除或替换字符串中的特定字符。
使用str.translate()和str.maketrans()
str.translate()乃是 Python 中用以高效处置字符串的方式,惯常与 str.maketrans()协同运用,旨在删减或更替字符串里的特定字符。其优势所在,乃是能够一次性地处置多个字符,性能颇为卓越。
static str.maketrans(x[, y[, z]])
This static method returns a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping
Unicode ordinals (integers) or characters (strings of length 1)
to Unicode ordinals, strings (of arbitrary lengths) or None.
Character keys will then be converted to ordinals.
If there are two arguments, they must be strings of equal length,
and in the resulting dictionary, each character in x will
be mapped to the character at the same position in y.
If there is a third argument, it must be a string,
whose characters will be mapped to None in the result.
str.maketrans 会返回一个能够应用于 str.translate 函数的翻译表。它能够接收一个、两个以及三个参数。当接收一个参数时,此参数务必为一个字典,该字典乃是从 Unicode 序数(整数)或者字符至 Unicode 序数、字符串或 None 的映射。当接收两个参数时,这两个参数必须是长度相等的字符串,于所得的结果字典中,x 里的字符将会被映射至 y 中相同位置上的字符。当接收三个参数时,最后的参数是一个字符串,结果字典中其被映射为 None 。
str.translate(table)
Return a copy of the string in which each character has been mapped
through the given translation table. The table must be an object that
implements indexing via __getitem__(), typically a mapping or sequence.
When indexed by a Unicode ordinal (an integer),
the table object can do any of the following: return a Unicode ordinal or a string,
to map the character to one or more other characters; return None,
to delete the character from the return string; or raise a LookupError exception,
to map the character to itself.
str.translate(table) 函数使用 table 作为翻译表,对原字符串中的内容进行替换,而被映射为 None 的字符会被删除。
将字符串中的某些字符替换为其他字符:
# 将 a -> 1, b -> 2, c -> 3
translation_table = str.maketrans("abc", "123")
text = "a quick brown fox"
cleaned_text = text.translate(translation_table)
print(cleaned_text) # 输出: 1 qui3k 2rown fox
删除字符串中的某些字符:
# 删除 a, b, c
translation_table = str.maketrans("", "", "abc")
text = "a quick brown fox"
cleaned_text = text.translate(translation_table)
print(cleaned_text) # 输出: quik rown fox
方法对比
方法 | 适用场景 | 优点 | 缺点 |
str.replace() | 删除或替换特定字符 | 简单直接 | 只能处理单个字符或固定字符串 |
str.translate() | 高效删除多个字符 | 性能高 | 需要创建翻译表 |
str.strip() | 删除开头和结尾的字符 | 简单直接 | 仅适用于开头和结尾的字符 |