如何在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)
这将取代一个空间中的双精度空间,直到不再有双精度空间
其他回答
要移除字符串周围的所有空白,请使用.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()方法(删除所有周围的空白)
str = " Hello World "
str = str.strip()
**result: str = "Hello World"**
请注意,.strip()返回字符串的副本,并且不会更改下划线对象(因为字符串是不可变的)。
如果您希望删除所有空白(不仅仅是修剪边缘):
str = ' abcd efgh ijk '
str = str.replace(' ', '')
**result: str = 'abcdefghijk'
你需要strip():
myphrases = [" Hello ", " Hello", "Hello ", "Bob has a cat"]
for phrase in myphrases:
print(phrase.strip())
这将删除myString中所有前导和尾部的空格:
myString.strip()
这也可以用正则表达式来实现
import re
input = " Hello "
output = re.sub(r'^\s+|\s+$', '', input)
# output = 'Hello'