我想仅使用for/while
循环和if
语句删除字符串中的额外空格;没有拆分/替换/加入。
mystring = 'Here is some text I wrote '
while ' ' in mystring:
mystring = mystring.replace(' ', ' ')
print(mystring)
输出
Here is some text I wrote
这是我尝试过的。不幸的是,它不太有效。
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
lasti = i
result += i
print(result)
cleanupstring("Hello my name is joe")
输出
Hello my name is joe
我的尝试不会删除所有额外的空格。
答案 0 :(得分:4)
将您的代码更改为:
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
print(result)
答案 1 :(得分:1)
检查当前字符和下一个字符是否为空格,如果不是,请将它们添加到干净的字符串中。在这种情况下确实不需要and
,因为我们正在比较相同的值
def cleanWhiteSpaces(str):
clean = ""
for i in range(len(str)):
if not str[i]==" "==str[i-1]:
clean += str[i]
return clean
答案 2 :(得分:1)
使用result
的末尾代替lasti
:
def cleanupstring(S):
result = S[0]
for i in S[1:]:
if not (result[-1] == " " and i == " "):
result += i
print(result)
cleanupstring("Hello my name is joe")
答案 3 :(得分:-1)
t =“你好,我叫乔”
“” .join(t.split())
“你好,我叫乔”