如何从 Python 中的字符串中删除前导和尾随空格?
例如:
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
只是一个空格还是所有连续的空格?如果是第二个,那么字符串已经有一个.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'
正如上面的答案所指出的
my_string.strip()
将删除所有前导和尾随空白字符,例如\n
, \r
, \t
, \f
, space
。
为了获得更大的灵活性,请使用以下
my_string.lstrip()
my_string.rstrip()
my_string.strip('\n')
或my_string.lstrip('\n\r')
或my_string.rstrip('\n\t')
等等。文档中提供了更多详细信息。
strip
也不限于空白字符:
# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
这将删除所有前导和尾随空格myString
:
myString.strip()
你想要strip()
:
myphrases = [" Hello ", " Hello", "Hello ", "Bob has a cat"]
for phrase in myphrases:
print(phrase.strip())
这也可以用正则表达式来完成
import re
input = " Hello "
output = re.sub(r'^\s+|\s+$', '', input)
# output = 'Hello'
好吧,作为初学者看到这个线程让我头晕目眩。因此想出了一个简单的捷径。
尽管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 中继承相同内容时可能会有所帮助。职能。
为了删除在 Pyhton 中运行完成的代码或程序时会导致大量缩进错误的“空白”。只需执行以下操作;显然,如果 Python 一直告诉错误是第 1、2、3、4、5 行等中的缩进...,只需来回修复该行。
但是,如果您仍然遇到与输入错误、运算符等相关的程序问题,请确保您阅读了 Python 对您大喊大叫的原因:
首先要检查的是您的缩进是否正确。如果这样做,请检查代码中是否有混合制表符和空格。
请记住:代码看起来不错(对您而言),但解释器拒绝运行它。如果你怀疑这一点,一个快速的解决方法是将你的代码带入一个空闲的编辑窗口,然后从菜单系统中选择 Edit..."Select All 从菜单系统中选择 Format..."Untabify Region。如果您将制表符与空格混合在一起,这将一次性将所有制表符转换为空格(并修复任何缩进问题)。
我找不到我正在寻找的解决方案,所以我创建了一些自定义函数。你可以试一试。
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()
就会找到。
我想删除字符串中过多的空格(也在字符串之间,不仅在开头或结尾)。我做了这个,因为我不知道该怎么做:
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)
这将替换一个空格中的双空格,直到您不再有双空格