Friday, August 2, 2019

python - How do I trim whitespace from a string?



How do I remove leading and trailing whitespace from a string in Python?



For example:



" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"


Answer



Just one space, or all consecutive spaces? If the second, then strings already have a .strip() method:



>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'

>>> ' Hello '.strip() # ALL consecutive spaces at both ends removed
'Hello'


If you need only to remove one space however, you could do it with:



def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s


>>> strip_one_space(" Hello ")
' Hello'


Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:



>>> "  Hello\n".strip(" ")
'Hello\n'


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...