如何在Python中删除字符串的前导和尾随空白?
" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
如何在Python中删除字符串的前导和尾随空白?
" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
当前回答
一种方法是使用.strip()方法(删除所有周围的空白)
str = " Hello World "
str = str.strip()
**result: str = "Hello World"**
请注意,.strip()返回字符串的副本,并且不会更改下划线对象(因为字符串是不可变的)。
如果您希望删除所有空白(不仅仅是修剪边缘):
str = ' abcd efgh ijk '
str = str.replace(' ', '')
**result: str = 'abcdefghijk'
其他回答
要移除字符串周围的所有空白,请使用.strip()。例子:
>>> ' 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'
注意str.strip()删除所有空白字符,包括制表符和换行符。若要仅删除空格,请指定要删除的特定字符作为strip的参数:
>>> " Hello\n ".strip(" ")
'Hello\n'
最多只删除一个空格:
def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
Strip也不局限于空白字符:
# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
我无法找到我正在寻找的解决方案,所以我创建了一些自定义函数。你可以试试。
def cleansed(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
# return trimmed(s.replace('"', '').replace("'", ""))
return trimmed(s)
def trimmed(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
ss = trim_start_and_end(s).replace(' ', ' ')
while ' ' in ss:
ss = ss.replace(' ', ' ')
return ss
def trim_start_and_end(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
return trim_start(trim_end(s))
def trim_start(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
chars = []
for c in s:
if c is not ' ' or len(chars) > 0:
chars.append(c)
return "".join(chars).lower()
def trim_end(s: str):
""":param s: String to be cleansed"""
assert s is not (None or "")
chars = []
for c in reversed(s):
if c is not ' ' or len(chars) > 0:
chars.append(c)
return "".join(reversed(chars)).lower()
s1 = ' b Beer '
s2 = 'Beer b '
s3 = ' Beer b '
s4 = ' bread butter Beer b '
cdd = trim_start(s1)
cddd = trim_end(s2)
clean1 = cleansed(s3)
clean2 = cleansed(s4)
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))
一种方法是使用.strip()方法(删除所有周围的空白)
str = " Hello World "
str = str.strip()
**result: str = "Hello World"**
请注意,.strip()返回字符串的副本,并且不会更改下划线对象(因为字符串是不可变的)。
如果您希望删除所有空白(不仅仅是修剪边缘):
str = ' abcd efgh ijk '
str = str.replace(' ', '')
**result: str = 'abcdefghijk'
好吧,作为一个初学者,看到这个帖子让我头晕目眩。于是我想到了一个简单的捷径。
虽然str.strip()可以移除开头和结尾的空格,但它对字符之间的空格没有任何作用。
words=input("Enter the word to test")
# If I have a user enter discontinous threads it becomes a problem
# input = " he llo, ho w are y ou "
n=words.strip()
print(n)
# output "he llo, ho w are y ou" - only leading & trailing spaces are removed
相反,使用str.replace()更有意义,错误更少,更切题。 下面的代码可以泛化str.replace()的使用
def whitespace(words):
r=words.replace(' ','') # removes all whitespace
n=r.replace(',','|') # other uses of replace
return n
def run():
words=input("Enter the word to test") # take user input
m=whitespace(words) #encase the def in run() to imporve usability on various functions
o=m.count('f') # for testing
return m,o
print(run())
output- ('hello|howareyou', 0)
在diff. functions中继承相同的函数时可以很有帮助。