Ufo*_*guy 2 python string whitespace python-2.7 python-3.x
我需要从python中的字符串中删除空格.例如.
str1 = "TN 81 NZ 0025"
str1sp = nospace(srt1)
print(str1sp)
>>>TN81NZ0025
Run Code Online (Sandbox Code Playgroud)
Ash*_*ary 20
用途str.replace:
>>> s = "TN 81 NZ 0025"
>>> s.replace(" ", "")
'TN81NZ0025'
Run Code Online (Sandbox Code Playgroud)
要删除所有类型的空白字符,请使用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'
Run Code Online (Sandbox Code Playgroud)
您可以用以下string.replace()函数替换每个空格:
>>> "TN 81 NZ 0025".replace(" ", "")
'TN81NZ0025'
Run Code Online (Sandbox Code Playgroud)
或者每个空格字符(包括\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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56957 次 |
| 最近记录: |