[英]Removing White Spaces in a Python String
通常的問題是從python字符串中刪除所有多余的空格,以便每個單詞之間只有一個空格,而字符串的開頭或結尾沒有空格。
例如,“向世界問好”將返回為“向世界問好”
我們不允許使用split命令,也不能使用基本字符串運算符(長度和並發)以及if和while命令以外的任何命令。
我已經編寫了程序,以便刪除字符串開頭的空格以及單詞之間的多余空格,但是,如果我在輸入字符串的最后一個單詞之后甚至還有一個空格,程序將返回錯誤“ index [ i]超出范圍”。
這是我的程序:
def cleanstring (s):
i=0
while s[i]==' ':
i=i+1
s=s[i:len(s)]
i=0
while i<len(s):
if s[i]!=' ':
i=i+1
else:
if i<len(s) and s[i]==' ':
i=i+1
if s[i]==' ' and i+1<len(s):
s=s[0:i]+s[i+1:len(s)]
i=0
return(s)
希望有人可以幫助我確定問題所在。 似乎我已經嘗試了所有方法,但我知道這只是我對python的經驗。
實際上有一個簡單而聰明的修復方法。 更改
if s[i]==' ' and i+1<len(s):
至...
if i<len(s) and s[i]==' ':
這是有效的,因為Python會短路, and
在任何時候都遇到偽造的值。 這意味着在i<len(s)
計算為False並且Python遇到and
,它將立即移至elif
或else
子句(如果有)。 因此,后半部分從不評估,因此沒有IndexError
。
現在,該程序無法正常運行。 還有其他的問題,但因為這是一個家庭作業,我不願意提供任何更多的幫助。 除了這個提示:您還需要另一個while循環。
您需要在另外一個地方檢查您的i是否在范圍內。 試一下:
def cleanstring(s):
i=0
while s[i]==' ':
i=i+1
s=s[i:len(s)]
i=0
while i<len(s):
if s[i]==' ':
if (i+1)<len(s) and s[i+1]==' ':
s=s[0:i]+s[i+1:len(s)]
else:
i=i+1
else:
i=i+1
if s[len(s)-1]==' ':
s=s[0:len(s)-1]
return(s)
這是您的實現結構,並進行了必要的更改:
def cleanstring (s):
i=0
while s[i]==' ':
i=i+1
s=s[i:len(s)]
i=0
while i<len(s):
if s[i]!=' ':
i=i+1
else:
if i<len(s) and s[i]==' ':
i=i+1
if i<len(s) and s[i]==' ':
s=s[0:i]+s[i+1:len(s)]
i=0
if s[-1] == ' ':
s = s[:-1]
return(s)
更改的是:
if s[i]==' ' and i+1<len(s):
至:
if i<len(s) and s[i]==' ':
但這將在最后保留一個空間,因此
if s[-1] == ' ':
s = s[:-1]
請享用。
這似乎工作正常。 看看這個。 repr()只是將字符串用引號引起來,以便查看單詞前后的實際空格數。
def cleanstring (s):
hit_letter = False
space_counter = 0
tmp = list()
for letter in s:
if letter.isalpha():
space_counter = 0
hit_letter = True
tmp.append(letter)
print letter
elif hit_letter:
space_counter += 1
if space_counter < 2:
tmp.append(letter)
return ''.join(tmp[:-1])
print repr(cleanstring(' Hi to the world '))
使用一些遞歸
def cleanString(word):
if word[0]==" ":
if len(word)>1:
return cleanString(word[1:])
return word[1:]
elif len(word)>1:
return word[0]+cleanString(word[1:])
return word
print cleanString(" abcd ") == "abcd" # True
print cleanString(" abcd ") # abcd
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.