'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)? For example:
string1 = ' a b '
I want the result:
#list1=[a,b]
When I test I found out that list1=string1.split() is enough. But somehow my teacher say string1.strip().split() is needed. Maybe he is wrong?
Solution 1:[1]
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.
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.
Solution 2:[2]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ewz93 |
| Solution 2 |
