Skip to main content
 首页 » 编程设计

python之在python中删除字符串中的空格和制表符

2025年05月04日19Leo_wl

如何在 python 中删除字符串中的特定空格。

我的输入字符串是:,

str1 = """vendor_id\t: GenuineIntel 
        cpu family\t: 6 
        model\t\t: 58 
        model name\t: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz 
        stepping\t: 9 
        cpu MHz\t\t: 2485.659 
        cache size\t: 6144 KB 
        fpu\t\t: yes 
        fpu_exception\t: yes 
        cpuid level\t: 5 
        wp\t\t: yes""" 

我需要的输出是:

>>>print str1 
vendor_id: GenuineIntel 
cpu family: 6 
model: 58 
model name: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz 
stepping: 9 
cpu MHz: 2485.659 
cache size: 6144 KB 
fpu: yes 
fpu_exception: yes 
cpuid level: 5 
wp: yes 

请您参考如下方法:

看起来你想删除行首的空格,并删除冒号前的所有空格。使用正则表达式:

import re 
 
re.sub(r'(^[ \t]+|[ \t]+(?=:))', '', str1, flags=re.M) 

这会在行首挑出空格和制表符(^[\t]*,^ 是行首,[\t ] 是一个空格或制表符,+ 是 1 个或多个),或者它会在冒号之前挑选出空格和制表符([\t ]+ 是 1 个或多个空格和制表符,(?=:) 表示 : 字符必须跟在后面但不包含在所选择的内容中)然后用空字符串替换那些空格和制表符。 flags=re.M 用于确保该模式适用于每一行。

演示:

>>> import re 
>>> str1 = """vendor_id\t: GenuineIntel 
...         cpu family\t: 6 
...         model\t\t: 58 
...         model name\t: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz 
...         stepping\t: 9 
...         cpu MHz\t\t: 2485.659 
...         cache size\t: 6144 KB 
...         fpu\t\t: yes 
...         fpu_exception\t: yes 
...         cpuid level\t: 5 
...         wp\t\t: yes""" 
>>> print re.sub(r'(^[ \t]+|[ \t]+(?=:))', '', str1, flags=re.M) 
vendor_id: GenuineIntel 
cpu family: 6 
model: 58 
model name: Intel(R) Core(TM) i3-3120M CPU @ 2.50GHz 
stepping: 9 
cpu MHz: 2485.659 
cache size: 6144 KB 
fpu: yes 
fpu_exception: yes 
cpuid level: 5 
wp: yes 

如果您的输入字符串不有前导空格(并且您只是自己缩进了示例以使其看起来对齐),那么您想要删除的只是制表符:

str1 = str1.replace('\t', '') 

并完成它。