2024-10-05 14:29:14 发布
网友
我需要在python中从字符串中删除空格。例如。
str1 = "TN 81 NZ 0025" str1sp = nospace(srt1) print(str1sp) >>>TN81NZ0025
请注意,在python中字符串是不可变的,string replace函数返回一个带有替换值的字符串。如果不是在shell中执行语句,而是在文件中执行
new_str = old_str.replace(" ","" )
这将替换字符串中的所有空格。如果你只想替换前n个空格
new_str = old_str.replace(" ","", n)
其中n是一个数字。
使用str.replace:
str.replace
>>> s = "TN 81 NZ 0025" >>> s.replace(" ", "") 'TN81NZ0025'
要删除所有类型的空白字符,请使用str.translate:
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):
\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中字符串是不可变的,string replace函数返回一个带有替换值的字符串。如果不是在shell中执行语句,而是在文件中执行
这将替换字符串中的所有空格。如果你只想替换前n个空格
其中n是一个数字。
使用
str.replace
:要删除所有类型的空白字符,请使用
str.translate
:可以用^{} function 替换每个空格:
或者每个带有regex的空白外壳(包括
\t
和\n
):相关问题 更多 >
编程相关推荐