简体   繁体   English

Split vs Strip in Python 去除多余的空白

[英]Split vs Strip in Python to remove redundant white space

May I ask do I need to use strip() before split() to remove any redundant space in Python (and turn into a list after)?请问我是否需要在split()之前使用strip()去除Python中的任何多余空间(之后变成列表)? For example:例如:

string1 = '   a      b '

I want the result:我想要结果:

#list1=[a,b]

When I test I found out that list1=string1.split() is enough.当我测试时,我发现list1=string1.split()就足够了。 But somehow my teacher say string1.strip().split() is needed.但不知何故,我的老师说string1.strip().split() Maybe he is wrong?也许他错了?

According to the documentation :根据文档

If sep is not specified or is None , a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.如果sep未指定或为None ,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随空格,则结果将在开头或结尾不包含空字符串。

Which means, that the logic of strip() is already included into split() , so I think, your teacher is wrong.这意味着, strip()的逻辑已经包含在split()中,所以我认为,你的老师错了。 (Notice, that this will change in case if you're using a non-default separator.) (请注意,如果您使用的是非默认分隔符,这将会改变。)

https://docs.python.org/3/library/stdtypes.html#str.split https://docs.python.org/3/library/stdtypes.html#str.split

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.如果 sep 未指定或为 None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随空格,则结果将在开头或结尾不包含空字符串。

You are right (at least for the case of using the default split by whitespace).你是对的(至少在使用默认的空格分割的情况下)。 Leading and trailing as well as consecutive whitescapes are ignored, and since .strip() does nothing else than remove leading and trailing whitespaces, it will result in the same output here.忽略前导和尾随以及连续的空白字符,并且由于.strip()除了删除前导和尾随空格外什么都不做,它会在此处产生相同的 output。

I tried using:我尝试使用:

string1 = '   a      b '
list1 = string1.strip().split()
print(list1)

and

string1 = '   a      b '
list1 = string1.split()
print(list1)

And they give the same result.他们给出了相同的结果。

So using strip() isn't necessarily needed, as it will only remove the spaces at the start (leading whitespaces) and spaces at the end (trailing whitespaces).因此不一定需要使用strip() ,因为它只会删除开头的空格(前导空格)和末尾的空格(尾随空格)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM