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

2024-10-05 14:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

str1 = "TN 81 NZ 0025"

str1sp = nospace(srt1)

print(str1sp)

>>>TN81NZ0025

Tags: 字符串tn空格printnzstr1nospacesrt1
3条回答

请注意,在python中字符串是不可变的,string replace函数返回一个带有替换值的字符串。如果不是在shell中执行语句,而是在文件中执行

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

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

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

其中n是一个数字。

使用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'

可以用^{} function替换每个空格:

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

或者每个带有regex的空白外壳(包括\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'

相关问题 更多 >