如何在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"
当前回答
我想删除字符串中过多的空格(也在字符串之间,而不仅仅是在开头或结尾)。我做了这个,因为我不知道该怎么做:
string = "Name : David Account: 1234 Another thing: something "
ready = False
while ready == False:
pos = string.find(" ")
if pos != -1:
string = string.replace(" "," ")
else:
ready = True
print(string)
这将取代一个空间中的双精度空间,直到不再有双精度空间
其他回答
如果你想从左边和右边修剪指定数量的空格,你可以这样做:
def remove_outer_spaces(text, num_of_leading, num_of_trailing):
text = list(text)
for i in range(num_of_leading):
if text[i] == " ":
text[i] = ""
else:
break
for i in range(1, num_of_trailing+1):
if text[-i] == " ":
text[-i] = ""
else:
break
return ''.join(text)
txt1 = " MY name is "
print(remove_outer_spaces(txt1, 1, 1)) # result is: " MY name is "
print(remove_outer_spaces(txt1, 2, 3)) # result is: " MY name is "
print(remove_outer_spaces(txt1, 6, 8)) # result is: "MY name is"
正如上面的答案所指出的
my_string.strip()
将删除所有前导和后面的空白字符,如\n, \r, \t, \f,空格。
为了获得更大的灵活性,请使用以下方法
只删除前导空白字符: 只移除尾随的空格字符: 删除特定的空白字符:my_string.strip('\n')或my_string.lstrip('\n\r')或my_string.rstrip('\n\t')等。
更多细节可以在文档中找到。
这将删除myString中所有前导和尾部的空格:
myString.strip()
我想删除字符串中过多的空格(也在字符串之间,而不仅仅是在开头或结尾)。我做了这个,因为我不知道该怎么做:
string = "Name : David Account: 1234 Another thing: something "
ready = False
while ready == False:
pos = string.find(" ")
if pos != -1:
string = string.replace(" "," ")
else:
ready = True
print(string)
这将取代一个空间中的双精度空间,直到不再有双精度空间
要移除字符串周围的所有空白,请使用.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'