繁体   English   中英

如何从Python中删除字符串中的空格?

[英]How to remove white spaces from a string in Python?

我需要从python中的字符串中删除空格。 例如。

str1 = "TN 81 NZ 0025"

str1sp = nospace(srt1)

print(str1sp)

>>>TN81NZ0025

使用str.replace

>>> s = "TN 81 NZ 0025"
>>> s.replace(" ", "")
'TN81NZ0025'

要删除所有类型的空白字符,请使用str.translate

>>> from string import whitespace
>>> s = "TN 81   NZ\t\t0025\nfoo"
# Python 2
>>> s.translate(None, whitespace)
'TN81NZ0025foo'
# Python 3
>>> s.translate(dict.fromkeys(map(ord, whitespace)))
'TN81NZ0025foo'

您可以通过string.replace()函数替换每个空格:

>>> "TN 81 NZ 0025".replace(" ", "")
'TN81NZ0025'

或者每个空格都有一个正则表达式(包括\\t\\n ):

>>> re.sub(r'\s+', '', "TN 81 NZ 0025")
'TN81NZ0025'
>>> re.sub(r'\s+', '', "TN 81 NZ\t0025")  # Note the \t character here
'TN81NZ0025'

请注意,python字符串是不可变的,字符串替换函数返回带有替换值的字符串。 如果您没有在shell中执行语句但在文件内部,

 new_str = old_str.replace(" ","" )

这将替换字符串中的所有空格。 如果你只想替换前n个空格,

new_str = old_str.replace(" ","", n)

其中n是数字。

一行代码删除句子之前,之后和之内的所有额外空格:

string = "  TN 81 NZ 0025  "
string = ''.join(filter(None,string.split(' ')))

说明:

  1. 将整个字符串拆分为列表。
  2. 从列表中过滤空元素。
  3. 没有任何东西重新加入剩余的元素

尝试这个:

s = "TN 81 NZ 0025"
s = ''.join(s.split())

您可以使用以下方法将多个空格替换为所需的模式。 这里你的模式是空白字符串。

import re
pattern = ""
re.sub(r"\s+", pattern, your_string)

要么

import re
pattern = ""
re.sub(r" +", "", your_string)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM