我如何修剪空白?

时间:2009-07-26 20:54:39

标签: python string whitespace trim strip

是否有Python函数可以从字符串中修剪空格(空格和制表符)?

示例:\t example string\texample string

16 个答案:

答案 0 :(得分:1477)

双方空白:

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

答案 1 :(得分:66)

Python trim方法称为strip

str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim

答案 2 :(得分:22)

对于前导和尾随空格:

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"

答案 3 :(得分:18)

您还可以使用非常简单的基本功能:str.replace(),使用空格和标签:

>>> whitespaces = "   abcd ef gh ijkl       "
>>> tabs = "        abcde       fgh        ijkl"

>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl

简单易行。

答案 4 :(得分:12)

#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 ']

答案 5 :(得分:4)

还没有人发布这些正则表达式解决方案。

匹配

>>> 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,则可能会移除内部空格,这可能是不受欢迎的。

答案 6 :(得分:3)

空白包括空格,制表符和CRLF 。因此,我们可以使用的优雅且单行字符串函数是翻译

' hello apple'.translate(None, ' \n\t\r')

如果您想要彻底

import string
' hello  apple'.translate(None, string.whitespace)

答案 7 :(得分:3)

  

(re.sub('+','',(my_str.replace('\ n','')))))。strip()

这将删除所有不需要的空格和换行符。希望有帮助

public List<MyObject> performSomeAction(){
    List<String> myList= Arrays.asList("abc","xyz","def");
    List<MyObject> resultList=new ArrayList<MyObject>();
    int startIndex=0;
    int totalNumOfRecords=1000; 
    for(int i=0;i<totalNumOfRecords;i++){
        SomeObject o= xService.doSomething();
        String type = o.getType();
        int length = o.getLength();
        if(myList.contains(type)){
            int[] myarray=getMyArray(startIndex+20, startIndex+length);
            String id=o.getSomeId();
            OtherObject obj= xService.performOperation(myarray,"abcd");
            resultList.add(new MyObject(obj,id));
        }
        startIndex+=length;
    }
    return resultList;
}

这将导致:

'a a b \ n c' 将更改为 'a b c'

答案 8 :(得分:2)

    something = "\t  please_     \t remove_  all_    \n\n\n\nwhitespaces\n\t  "

    something = "".join(something.split())

输出:   please_remove_all_whitespaces

答案 9 :(得分:2)

这里以不同的理解程度看了很多解决方案,我想知道如果字符串用逗号分隔该怎么办...

问题

在尝试处理联系人信息的csv时,我需要一个解决此问题的方法:修剪多余的空格和一些垃圾,但保留尾部逗号和内部空格。我要处理包含联系人注释的字段,所以我想删除垃圾,留下好东西。删除所有标点符号和谷壳后,我不想失去复合令牌之间的空白,因为我不想以后再构建。

正则表达式和模式:[\s_]+?\W+

该模式将查找任何空白字符的单个实例,并在非单词字符之前使用[\s_]+?来从1到下划线('_')到{发生在1到无限制时间之间的时间是:\W+(相当于[^a-zA-Z0-9_])。具体来说,这会找到大量空白:空字符(\ 0),制表符(\ t),换行符(\ n),前馈(\ f),回车符(\ r)。

我认为这样做有两个好处:

  1. 它不会删除您可能希望保留在一起的完整单词/标记之间的空格;

  2. Python的内置字符串方法strip()不在字符串内处理,仅在左右两端进行处理,默认arg为空字符(请参见以下示例:文本中有几行换行,并且strip()不会将它们全部删除,而regex模式会删除它们)。 text.strip(' \n\t\r')

这超出了OP的问题,但是我认为在很多情况下,像我一样,文本数据中可能会有奇怪的病理性实例(某些转义字符最终出现在某些文本中)。此外,在类似列表的字符串中,除非分隔符将两个空格字符或某些非单词字符分开,例如'-,'或'-、、、',否则我们不希望删除分隔符。

NB:不是在谈论CSV本身的分隔符。仅在CSV内数据类似于列表的实例,即c.s。一串子字符串。

全面披露:我只处理文本约一个月,而正则表达式仅在最近两周内处理,所以我确定我缺少一些细微差别。就是说,对于较小的字符串集合(我的字符串在12,000行和40个奇数列的数据框中),作为除去多余字符的最后一步,此方法效果很好,特别是如果您在其中引入了一些额外的空格想要分隔以非单词字符连接的文本,但又不想在以前没有空格的地方添加空格。

一个例子:

import re


text = "\"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, jim.somedude@blahblah.com, ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, , , , \r, , \0, ff dd \n invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, \n i69rpofhfsp9t7c practice 20ignition - 20june \t\n .2134.pdf 2109                                                 \n\n\n\nklkjsdf\""

print(f"Here is the text as formatted:\n{text}\n")
print()
print("Trimming both the whitespaces and the non-word characters that follow them.")
print()
trim_ws_punctn = re.compile(r'[\s_]+?\W+')
clean_text = trim_ws_punctn.sub(' ', text)
print(clean_text)
print()
print("what about 'strip()'?")
print(f"Here is the text, formatted as is:\n{text}\n")
clean_text = text.strip(' \n\t\r')  # strip out whitespace?
print()
print(f"Here is the text, formatted as is:\n{clean_text}\n")

print()
print("Are 'text' and 'clean_text' unchanged?")
print(clean_text == text)

这将输出:

Here is the text as formatted:

"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, jim.somedude@blahblah.com, ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf" 

using regex to trim both the whitespaces and the non-word characters that follow them.

"portfolio, derp, hello-world, hello-, world, founders, mentors, ffib, biff, 1, 12.18.02, 12, 2013, 9874890288, ff, series a, exit, general mailing, fr, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk,  jim.somedude@blahblah.com, dd invites,subscribed,, master, dd invites,subscribed, ff dd invites, subscribed, alumni spring 2012 deck: https: www.dropbox.com s, i69rpofhfsp9t7c practice 20ignition 20june 2134.pdf 2109 klkjsdf"

Very nice.
What about 'strip()'?

Here is the text, formatted as is:

"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, jim.somedude@blahblah.com, ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf"


Here is the text, after stipping with 'strip':


"portfolio, derp, hello-world, hello-, -world, founders, mentors, :, ?, %, ,>, , ffib, biff, 1, 12.18.02, 12,  2013, 9874890288, .., ..., ...., , ff, series a, exit, general mailing, fr, , , ,, co founder, pitch_at_palace, ba, _slkdjfl_bf, sdf_jlk, )_(, jim.somedude@blahblah.com, ,dd invites,subscribed,, master, , , ,  dd invites,subscribed, ,, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june 
 .2134.pdf 2109                                                 



klkjsdf"
Are 'text' and 'clean_text' unchanged? 'True'

因此,strip一次删除了一个空格。因此在OP的情况下,strip()很好。但是如果情况变得更复杂,则对于更常规的设置,正则表达式和类似的模式可能会有一定价值。

see it in action

答案 10 :(得分:1)

如果使用Python 3:在打印语句中,以sep =“”结尾。这将分隔所有空间。

示例:

txt="potatoes"
print("I love ",txt,"",sep="")

这将打印: 我爱土豆。

代替: 我爱土豆。

在您的情况下,由于您将尝试使用\ t,因此请执行sep =“ \ t”

答案 11 :(得分:0)

尝试翻译

>>> 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'

答案 12 :(得分:0)

如果只想在字符串的开头和结尾处修剪空格,则可以执行以下操作:

some_string = "    Hello,    world!\n    "
new_string = some_string.strip()
# new_string is now "Hello,    world!"

这与Qt的QString :: trimmed()方法非常相似,因为它删除了前导和尾随空格,而只保留了内部空格。

但是,如果您想使用类似Qt的QString :: simplified()方法的方法,该方法不仅可以删除开头和结尾的空格,还可以将所有连续的内部空格“压缩”为一个空格字符,则可以使用{{ 1}}和.split(),如下所示:

" ".join

在最后一个示例中,内部空格的每个序列都用一个空格代替,同时仍将字符串的开头和结尾处的空格修剪掉。

答案 13 :(得分:-1)

通常,我使用以下方法:

>>> 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'

注意:这仅用于删除&#34; \ n&#34;,&#34; \ r&#34;和&#34; \ t&#34;只要。它不会删除多余的空格。

答案 14 :(得分:-2)

用于从字符串中间删除空格

&#13;
&#13;
$p = "ATGCGAC ACGATCGACC";
$p =~ s/\s//g;
print $p;
&#13;
&#13;
&#13;

输出: ATGCGACACGATCGACC

答案 15 :(得分:-17)

这将从字符串的开头和结尾删除所有空格和换行符:

>>> s = "  \n\t  \n   some \n text \n     "
>>> re.sub("^\s+|\s+$", "", s)
>>> "some \n text"