去除所有空格 EXCLUDING 制表符
Strip all whitespaces EXCLUDING tabs
只是一个(希望)简单的问题。
弄乱 Python 我只想知道如何去除字符串左侧和右侧的所有空格 除了 制表符,或者更确切地说 \t
.
我知道我可以用替换递归循环,但这很麻烦。必须有更简单的方法。
基本上只删除 \n, ,\r,
...等 \t
.
除外
干杯。
使用re.sub
:
import re
string = 'Hello\nThis is a sample\tstring\n\r!'
print(re.sub('[ \n\r]', '', string))
您还可以使用:
s = " \t a string example\t "
s = s.strip(' \n\r')
这将从字符串的左侧、右侧或两侧去除任何 space、\n 或 \r 字符。
参考:How to trim whitespace (including tabs)?
s.strip(' ').strip('\n').strip('\r')#this will return a copy of string with '\r' and '\b' removed from left side and right side.
参见:string.strip
只是一个(希望)简单的问题。
弄乱 Python 我只想知道如何去除字符串左侧和右侧的所有空格 除了 制表符,或者更确切地说 \t
.
我知道我可以用替换递归循环,但这很麻烦。必须有更简单的方法。
基本上只删除 \n, ,\r,
...等 \t
.
除外
干杯。
使用re.sub
:
import re
string = 'Hello\nThis is a sample\tstring\n\r!'
print(re.sub('[ \n\r]', '', string))
您还可以使用:
s = " \t a string example\t "
s = s.strip(' \n\r')
这将从字符串的左侧、右侧或两侧去除任何 space、\n 或 \r 字符。
参考:How to trim whitespace (including tabs)?
s.strip(' ').strip('\n').strip('\r')#this will return a copy of string with '\r' and '\b' removed from left side and right side.
参见:string.strip