How do I trim whitespace from a Python 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"
Just one space, or all such 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 spaces at 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 (eg tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip
, ie:
>>> " Hellon".strip(" ")
'Hellon'
As pointed out in answers above
myString.strip()
will remove all the leading and trailing whitespace characters such as n, r, t, f, space.
For more flexibility use the following
myString.lstrip()
myString.rstrip()
myString.strip('n')
or myString.lstrip('nr')
or myString.rstrip('nt')
and so on. More details are available in the docs
strip
并不限于空白字符:
# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
链接地址: http://www.djcxy.com/p/66496.html
上一篇: 递归追溯返回类型?
下一篇: 如何修剪Python字符串中的空格?