是否有一个Python函数将从字符串中删除空白(空格和制表符)?
所以给定的输入" \t example string\t "变成了"example string"
是否有一个Python函数将从字符串中删除空白(空格和制表符)?
所以给定的输入" \t example string\t "变成了"example string"
当前回答
还没有人发布这些正则表达式的解决方案。
匹配:
>>> import re
>>> p=re.compile('\\s*(.*\\S)?\\s*')
>>> m=p.match(' \t blah ')
>>> m.group(1)
'blah'
>>> m=p.match(' \tbl ah \t ')
>>> m.group(1)
'bl ah'
>>> m=p.match(' \t ')
>>> print m.group(1)
None
搜索(你必须处理“只有空格”输入大小写不同):
>>> p1=re.compile('\\S.*\\S')
>>> m=p1.search(' \tblah \t ')
>>> m.group()
'blah'
>>> m=p1.search(' \tbl ah \t ')
>>> m.group()
'bl ah'
>>> m=p1.search(' \t ')
>>> m.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
如果使用re.sub,可能会删除内部空白,这可能是不可取的。
其他回答
#how to trim a multi line string or a file
s=""" line one
\tline two\t
line three """
#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.
s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']
print [i.strip() for i in s1]
['line one', 'line two', 'line three']
#more details:
#we could also have used a forloop from the begining:
for line in s.splitlines():
line=line.strip()
process(line)
#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
line=line.strip()
process(line)
#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']
一般来说,我使用的方法如下:
>>> myStr = "Hi\n Stack Over \r flow!"
>>> charList = [u"\u005Cn",u"\u005Cr",u"\u005Ct"]
>>> import re
>>> for i in charList:
myStr = re.sub(i, r"", myStr)
>>> myStr
'Hi Stack Over flow'
注意:这只用于删除“\n”,“\r”和“\t”。它不会删除额外的空格。
空格包括空格、制表符和CRLF。我们可以使用一个优雅的单行字符串函数翻译。
你好。翻译(不,不,不)
或者,如果你想彻底一点
import string
' hello apple'.translate(None, string.whitespace)
前导空格和尾随空格:
s = ' foo \t '
print s.strip() # prints "foo"
否则,正则表达式工作:
import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s) # prints "foobar"
如果你想去掉字符串开头和结尾的空白,你可以这样做:
some_string = " Hello, world!\n "
new_string = some_string.strip()
# new_string is now "Hello, world!"
这很像Qt的QString::()方法,因为它删除了开头和结尾的空白,而只保留内部空白。
但是,如果你想使用Qt的QString::simplified()方法,它不仅删除开头和结尾的空白,而且还将所有连续的内部空白“压缩”为一个空格字符,你可以使用.split()和" "的组合。像这样加入:
some_string = "\t Hello, \n\t world!\n "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"
在最后一个示例中,每个内部空格序列都被替换为单个空格,同时仍然将字符串的开头和结尾的空白删除。