希望我的问题(希望)非常简单。
我在使用Python做一些混乱的事情,我想知道如何去除字符串左侧和右侧的所有空格,但不包括制表符,或者说\t
。
我知道我可能可以通过递归循环使用replace来解决,但那很凌乱。肯定有更简单的方法。
基本上只需删除\n, ,\r,
等,但不包括\t
。
干杯。
希望我的问题(希望)非常简单。
我在使用Python做一些混乱的事情,我想知道如何去除字符串左侧和右侧的所有空格,但不包括制表符,或者说\t
。
我知道我可能可以通过递归循环使用replace来解决,但那很凌乱。肯定有更简单的方法。
基本上只需删除\n, ,\r,
等,但不包括\t
。
干杯。
s = " \t a string example\t "
s = s.strip(' \n\r')
使用 re.sub
:
import re
string = 'Hello\nThis is a sample\tstring\n\r!'
print(re.sub('[ \n\r]', '', string))
s.strip(' ').strip('\n').strip('\r')#this will return a copy of string with '\r' and '\b' removed from left side and right side.
See:string.strip
\t
,但不会去除\b
,因为strip()
会去除所有的空白字符,包括制表符。 - Steve Barnes
strip()
函数可以带参数。 - user5549921