我如何修剪空白?
- 2025-01-17 09:23:00
- admin 原创
- 118
问题描述:
是否有一个 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)。
我认为这样做有两方面的好处:
它不会删除您可能想要保留在一起的完整单词/标记之间的空格;
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"