Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-仅使用循环删除空白_Python - Fatal编程技术网

Python-仅使用循环删除空白

Python-仅使用循环删除空白,python,Python,我想只使用for/while循环和if语句删除字符串中的额外空格;没有拆分/替换/连接 像这样: mystring = 'Here is some text I wrote ' while ' ' in mystring: mystring = mystring.replace(' ', ' ') print(mystring) 输出: 这是我试过的。不幸的是,它不太管用 def cleanupstring(S): lasti = ""

我想只使用for/while循环和if语句删除字符串中的额外空格;没有拆分/替换/连接

像这样:

mystring = 'Here is  some   text   I      wrote   '

while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

print(mystring)
输出:

这是我试过的。不幸的是,它不太管用

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")
输出:


我的尝试不会删除所有多余的空格。

将代码更改为:

    for i in S:
        if lasti == " " and i == " ":
            i = ""
        else:
            lasti = i    
        result += i    

    print(result)

将代码更改为:

    for i in S:
        if lasti == " " and i == " ":
            i = ""
        else:
            lasti = i    
        result += i    

    print(result)

检查当前字符和下一个字符是否为空格,如果不是,请将它们添加到干净的字符串中。在这种情况下,确实不需要and,因为我们将与相同的值进行比较

def cleanWhiteSpaces(str):
  clean = ""
  for i in range(len(str)):
    if not str[i]==" "==str[i-1]:
      clean += str[i]
  return clean

检查当前字符和下一个字符是否为空格,如果不是,请将它们添加到干净的字符串中。在这种情况下,确实不需要and,因为我们将与相同的值进行比较

def cleanWhiteSpaces(str):
  clean = ""
  for i in range(len(str)):
    if not str[i]==" "==str[i-1]:
      clean += str[i]
  return clean
使用结果结尾代替lasti:

使用结果结尾代替lasti:

试试这个 你好,我叫乔

.关节

这将输出 你好,我叫乔,试试这个 你好,我叫乔

.关节

这将输出
你好,我的名字是joe

我想这是某种学习练习,因为我可能只会使用正则表达式。在设置lasti之前,您正在更新I。我想这是某种学习练习,因为我可能只会使用正则表达式。在设置lasti之前,您正在更新I。它不会在第一次迭代时比较最后一个字符吗?因为S[-1]给了您最后一个字符。您是对的,范围需要从1开始,而不是从0开始,实际上毫无理由地更改了它不会在第一次迭代时比较最后一个字符吗[-1]给你最后一个字符?你是对的,range需要从1开始,而不是0,实际上毫无理由地改变了它fwiw:错误是当你设置i=,你以后设置lasti=i。这意味着lasti不再是一个空格,因此下一次出现空格时,你的测试条件就不满足了。将else放在两个路径中会分开s、 当一个空格被忽略时,将lasti设置为space。@RaminNietzsche我在解释为什么您的代码可以工作,而原始代码不能工作。FWIW:错误在于,当您设置I=,您以后将设置lasti=I。这意味着lasti不再是一个空格,因此下次出现空格时,您的测试条件将不满足。将else in分隔两条路径,并在忽略空格时将lasti设置为space。@RaminNietzsche我刚才解释了为什么代码可以工作,而原始代码不能工作。
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")