是否有Python函数可以从字符串中修剪空白(空格和制表符)?
示例: \\t example string\\t
→ example string
#1楼
对于前导和尾随空格:
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"
#2楼
两侧的空格:
s = " \t a string example\t "
s = s.strip()
右侧的空格:
s = s.rstrip()
左侧的空白:
s = s.lstrip()
正如thedz所指出的,您可以提供一个参数来将任意字符剥离到以下任何函数中,如下所示:
s = s.strip(' \t\n\r')
这将从字符串的左侧,右侧或两侧去除所有空格, \\t
, \\n
或\\r
字符。
上面的示例仅从字符串的左侧和右侧删除字符串。 如果您还想从字符串中间删除字符,请尝试re.sub
:
import re
print re.sub('[\s+]', '', s)
那应该打印出来:
astringexample
#3楼
尚无人发布这些正则表达式解决方案。
匹配:
>>> 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
,则可能会删除内部空格,这可能是不希望的。
#4楼
您还可以使用非常简单且基本的功能: str.replace() ,用于空白和制表符:
>>> whitespaces = " abcd ef gh ijkl "
>>> tabs = " abcde fgh ijkl"
>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl
简单容易。
#5楼
尝试翻译
>>> import string
>>> print '\t\r\n hello \r\n world \t\r\n'
hello
world
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr)
' hello world '
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'
#6楼
something = "\t please_ \t remove_ all_ \n\n\n\nwhitespaces\n\t "
something = "".join(something.split())
输出:
please_remove_all_whitespaces
在答案中添加Le Droid的评论。 用空格分隔:
something = "\\t please \\t remove all extra \\n\\n\\n\\nwhitespaces\\n\\t " something = " ".join(something.split())
输出:
请删除所有多余的空格
#7楼
通常,我使用以下方法:
>>> 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”。 它不会删除多余的空间。
#8楼
空格包括空格,制表符和CRLF 。 因此,我们可以使用的一种优雅且单线的字符串函数是translation 。
' hello apple'.translate(None, ' \\n\\t\\r')
或者,如果您想彻底
import string
' hello apple'.translate(None, string.whitespace)
#9楼
这将删除字符串开头和结尾的所有空格和换行符:
>>> s = " \n\t \n some \n text \n "
>>> re.sub("^\s+|\s+$", "", s)
>>> "some \n text"
#10楼
用于从字符串中间删除空格
$p = "ATGCGAC ACGATCGACC";
$p =~ s/\s//g;
print $p;
输出:
ATGCGACACGATCGACC
#11楼
(re.sub('+','',(my_str.replace('\\ n',''))))。strip()
这将删除所有不需要的空格和换行符。 希望这个帮助
import re
my_str = ' a b \n c '
formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()
这将导致:
'a b \\ nc' 将更改为 'ab c'
#12楼
如果使用Python 3:在您的打印语句中,以sep =“”结尾。 这将分隔所有空间。
例:
txt="potatoes"
print("I love ",txt,"",sep="")
这将打印:我爱土豆。
代替:我爱土豆。
在您的情况下,由于您将尝试使用\\ t,因此请执行sep =“ \\ t”
#13楼
如果要仅在字符串的开头和结尾处修剪空格,可以执行以下操作:
some_string = " Hello, world!\n "
new_string = some_string.strip()
# new_string is now "Hello, world!"
它的工作原理与Qt的QString :: trimmed()方法非常相似,因为它除去了前导和尾随的空格,而仅保留内部空格。
但是,如果您想使用类似Qt的QString :: simplified()方法的方法,该方法不仅删除开头和结尾的空格,还可以将所有连续的内部空格“压缩”到一个空格字符,则可以使用.split()
和" ".join
,像这样:
some_string = "\t Hello, \n\t world!\n "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"
在最后一个示例中,内部空格的每个序列都用单个空格替换,同时仍在字符串的开头和结尾修剪空格。
#14楼
#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 ']
#15楼
Python trim
方法称为strip
:
str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim