如何在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)

这将取代一个空间中的双精度空间,直到不再有双精度空间

其他回答

这将删除myString中所有前导和尾部的空格:

myString.strip()

在Pyhton中运行完成的代码或程序时,为了删除会导致大量缩进错误的“空白”。只需执行以下操作;显然,如果Python一直告诉我们错误是第1、2、3、4、5行中的缩进,等等……把那条线来回固定。

然而,如果你仍然遇到与输入错误、操作符等相关的程序问题,请确保你阅读了错误Python为什么对你大喊大叫:

首先要检查的是你是否有 缩进。如果你有,那么检查一下你是否有 在代码中混合制表符和空格。

记住:代码 将看起来很好(对您),但解释器拒绝运行它。如果 如果你怀疑这一点,一个快速的解决方法就是把你的代码带入 IDLE编辑窗口,然后选择编辑…“从 菜单系统,在选择格式之前…“Untabify地区。 如果你混合了制表符和空格,这将转换你所有的 制表符到空格一次性完成(并修复任何缩进问题)。

Strip也不局限于空白字符:

# remove all leading/trailing commas, periods and hyphens
title = title.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)

这将取代一个空间中的双精度空间,直到不再有双精度空间

好吧,作为一个初学者,看到这个帖子让我头晕目眩。于是我想到了一个简单的捷径。

虽然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中继承相同的函数时可以很有帮助。