Answers:
只是一个空格,还是所有连续的空格?如果是第二个,则字符串已经具有.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'
但是,如果只需要删除一个空格,可以使用以下方法:
def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
另外,请注意,str.strip()
它也会删除其他空白字符(例如,制表符和换行符)。要仅删除空格,您可以指定要删除的字符作为的参数strip
,即:
>>> " Hello\n".strip(" ")
'Hello\n'
rstrip()
功能。:-)
strip
而不是trim
,isinstance
不是instanceof
,list
不是array
,等,等,为什么不直接使用每个人都熟悉的名字?geez:P
strip
我完全同意@GershomMaes的观点,但是列表与数组完全不同。
正如以上答案中指出的
myString.strip()
将删除所有前导和尾随空格字符,例如\ n,\ r,\ t,\ f,空格。
为了获得更大的灵活性,请使用以下命令
myString.lstrip()
myString.rstrip()
myString.strip('\n')
或myString.lstrip('\n\r')
or myString.rstrip('\n\t')
等等。更多详细信息可在文档中找到
strip
不限于空白字符:
# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
这将删除以下所有开头和结尾的空格myString
:
myString.strip()
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)
这将在一个空间中替换双倍空格,直到您不再有双倍空格为止
我找不到想要的解决方案,所以我创建了一些自定义函数。您可以尝试一下。
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)))
如果要从left和right修剪指定数量的空格,可以执行以下操作:
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"
如何从Python中的字符串中删除开头和结尾的空格?
因此,下面的解决方案也将删除前导和尾随空格以及中间空格。就像您需要获取不带多个空格的清晰字符串值一样。
>>> str_1 = ' Hello World'
>>> print(' '.join(str_1.split()))
Hello World
>>>
>>>
>>> str_2 = ' Hello World'
>>> print(' '.join(str_2.split()))
Hello World
>>>
>>>
>>> str_3 = 'Hello World '
>>> print(' '.join(str_3.split()))
Hello World
>>>
>>>
>>> str_4 = 'Hello World '
>>> print(' '.join(str_4.split()))
Hello World
>>>
>>>
>>> str_5 = ' Hello World '
>>> print(' '.join(str_5.split()))
Hello World
>>>
>>>
>>> str_6 = ' Hello World '
>>> print(' '.join(str_6.split()))
Hello World
>>>
>>>
>>> str_7 = 'Hello World'
>>> print(' '.join(str_7.split()))
Hello World
如您所见,这将删除字符串中的所有多个空格(输出适用Hello World
于所有空格)。位置无关紧要。但是,如果您确实需要前导和尾随空格,那么strip()
就会发现。