Python 高效的删除字符串中不需要的字符

liftword1个月前 (03-23)技术文章8

处理字符串时常常需要删除一些不需要的字符,比如空格、标点符号、特殊符号等。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()

删除开头和结尾的字符

简单直接

仅适用于开头和结尾的字符

相关文章

python如何彻底卸载

要想彻底干净的卸载python,如果是使用的安装版的话,其实很简单。就是点击安装包。例如,当前你安装的版本是3.6.5,你想要把它卸载掉。查看python版本的命令:只需要点击对应版本的安装包:点击卸...

Python目录删除

def find_remaining_directories(m, relations, delete_id): # 构建目录树 tree = {} for child, pa...

如何干净删除python

先打开geek,趁着python没注意,咱们搞偷袭,右键一下子卸载掉然后打开everything,删掉c盘一些python主目录(以前安装的目录,如果删不掉,右键点开 在文件夹 安全里 调整下权限 之...

python删除文件和删除目录的方法

下面来看一下python里面是如何删除一个文件及文件夹的~~首先引入OS模块import os删除文件: os.remove()删除空目录: os.rmdir()递归删除空目录: os.removed...

新手教程系列之《卸载Python及pycharm》

本次分享为保姆式新手教程系列之《卸载Python及pycharm》大神请略过O(∩_∩)O 哈哈!本次安装电脑配置:windows10 64位操作系统运行内存:8g步骤演示:点击左下角开始(或者按键盘...

Linux系统自带Python2&yum的卸载及重装

写在前面事情的起因是我昨天在测试Linux安装Python3的shell脚本时,需要卸载Python3重新安装一遍。但是通过如下命令卸载python3时,少写了个3,不小心将系统自带的python2也...