我如何修剪空白?

2025-01-17 09:23:00
admin
原创
118
摘要:问题描述:是否有一个 Python 函数可以从字符串中修剪空白(空格和制表符)?这样给定的输入" example string "就变成了"example string"。解决方案 1:对于两侧的空格,使用str.strip:s = " ...

问题描述:

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

这样给定的输入" example string "就变成了"example string"


解决方案 1:

对于两侧的空格,使用str.strip

s = "       a string example      "
s = s.strip()

对于右侧的空格,使用str.rstrip

s = s.rstrip()

对于左侧的空格,使用str.lstrip

s = s.lstrip()

您可以向任何这些函数提供一个参数来删除任意字符,如下所示:

s = s.strip('     

')

这将删除字符串两边的任何空格 、、`
或字符。
`

上面的示例仅从字符串的左侧和右侧删除字符串。 如果您还想从字符串中间删除字符,请尝试re.sub

import re
print(re.sub('[s+]', '', s))

应该打印出:

astringexample

解决方案 2:

在 Python 中,trim方法名为strip

str.strip()  # trim
str.lstrip()  # left trim
str.rstrip()  # right trim

解决方案 3:

对于前导和尾随空格:

s = '   foo           '
print s.strip() # prints "foo"

否则,正则表达式有效:

import re
pat = re.compile(r's+')
s = '        foo          bar       '
print pat.sub('', s) # prints "foobar"

解决方案 4:

您还可以使用非常简单和基本的函数:str.replace(),它与空格和制表符一起使用:

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

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

簡單又容易。

解决方案 5:

#how to trim a multi line string or a file

s=""" line one
    line two    
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', '    line two    ', '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
', '    line two    
', 'line three ']

解决方案 6:

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

匹配:

>>> import re
>>> p=re.compile('\\s*(.*\\S)?\\s*')

>>> m=p.match('       blah ')
>>> m.group(1)
'blah'

>>> m=p.match('      bl ah       ')
>>> m.group(1)
'bl ah'

>>> m=p.match('        ')
>>> print m.group(1)
None

搜索(您必须以不同的方式处理“仅空格”输入情况):

>>> p1=re.compile('\\S.*\\S')

>>> m=p1.search('      blah       ')
>>> m.group()
'blah'

>>> m=p1.search('      bl ah       ')
>>> m.group()
'bl ah'

>>> m=p1.search('        ')
>>> m.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

如果您使用re.sub,您可能会删除内部空格,这可能是不受欢迎的。

解决方案 7:

空格包括空格、制表符和 CRLF。因此,我们可以使用一个优雅的单行字符串函数:translate

`' hello apple'.translate(None, '

')`

或者如果你想要彻底

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

解决方案 8:

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

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

import re
my_str = '   a     b 
 c   '
formatted_str = (re.sub(' +', ' ',(my_str.replace('
',' ')))).strip()

这将导致:

' a b \nc ' 将更改为 'ab c'

解决方案 9:

    something = "      please_          remove_  all_    



whitespaces
      "

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

输出:

请移除所有空白


将 Le Droid 的评论添加到答案中。用空格分隔:

    something = "      please          remove  all   extra 



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

输出:

请删除所有多余的空格

解决方案 10:

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

问题

在尝试处理联系人信息的 csv 时,我需要解决这个问题:删除多余的空格和一些垃圾,但保留尾随逗号和内部空格。处理包含联系人注释的字段时,我想删除垃圾,留下好东西。删除所有标点符号和无用信息,我不想丢失复合标记之间的空格,因为我不想稍后重建。

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

该模式会以尽可能少的字符查找任何空格字符和下划线 ('_') 的单个实例,查找次数从 1 次到无限次,[s_]+?查找出现在非单词字符之前,查找次数从 1 次到无限次,其方式如下:( W+相当于[^a-zA-Z0-9_])。具体来说,这会找到大片空格:空字符 (\0)、制表符 (\t)、换行符 (\n)、前馈 (\f)、回车符 (\r)。

我认为这样做有两方面的好处:

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

  2. Python 的内置字符串方法strip()不处理字符串内部,只处理左端和右端,默​​认参数为空字符(见以下示例:文本中有几个换行符,并且strip()不会像正则表达式模式那样将它们全部删除)。`text.strip('

    ')`

这超出了 OP 的问题,但我认为在很多情况下,我们可能会在文本数据中遇到奇怪的、病态的情况,就像我遇到的那样(转义字符以某种方式出现在某些文本中)。此外,在列表类字符串中,我们不想消除分隔符,除非分隔符分隔两个空格字符或某些非单词字符,如“-,”或“-, ,,,”。

注意:不讨论 CSV 本身的分隔符。仅讨论 CSV 中数据为列表形式的实例,即子字符串的 cs 字符串。

全面披露:我处理文本才一个月左右,处理正则表达式才两周,所以我肯定有些细微差别我没注意到。也就是说,对于较小的字符串集合(我的数据框有 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, , , , 
, , , ff dd 
 invites, subscribed, , ,  , , alumni spring 2012 deck: https: www.dropbox.com s, 
 i69rpofhfsp9t7c practice 20ignition - 20june     
 .2134.pdf 2109                                                 



klkjsdf\""

print(f"Here is the text as formatted:
{text}
")
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:
{text}
")
clean_text = text.strip(' 
    
')  # strip out whitespace?
print()
print(f"Here is the text, formatted as is:
{clean_text}
")

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()这样做没问题。但如果事情变得更加复杂,正则表达式和类似的模式可能对更一般的设置有一定价值。

观看实际操作

解决方案 11:

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

例子:

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

这将打印:
我爱土豆。

而不是:
我喜欢土豆。

在你的情况下,因为你试图摆脱 \t,所以做 sep="\t"

解决方案 12:

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

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

这与 Qt 的 QString::trimmed() 方法非常相似,它会删除前导和尾随空格,同时保留内部空格。

但是如果您想要类似 Qt 的 QString::simplified() 方法,它不仅可以删除前导和尾随空格,还可以将所有连续的内部空格“压缩”为一个空格字符,那么您可以使用.split()和的组合" ".join,如下所示:

some_string = "        Hello,  
      world!
    "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"

在最后一个例子中,每个内部空格序列都被一个空格替换,同时仍然修剪字符串开始和结束处的空格。

解决方案 13:

尝试翻译

>>> import string
>>> print '    
  hello 
 world     
'

  hello 
 world  
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '    
  hello 
 world     
'.translate(tr)
'     hello    world    '
>>> '    
  hello 
 world     
'.translate(tr).replace(' ', '')
'helloworld'

解决方案 14:

一般我都是采用下面的方法:

>>> myStr = "Hi
 Stack Over 
 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”。它不会删除多余的空格。

解决方案 15:

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

>>> s = "  
      
   some 
 text 
     "
>>> re.sub("^s+|s+$", "", s)
>>> "some 
 text"
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用