简体   繁体   English

如何使用枚举 function 和 for 循环从字符串中删除不需要的空格

[英]How can i remove unwanted spaces from the string using enumerate function and for loop

i have this code but it is not working.. i don't know what's wrong in this code我有这段代码,但它不起作用..我不知道这段代码有什么问题

djtext = "g o d  i s   gre at"
analyzed = ""
for index, char in enumerate(djtext):
    if not(djtext[index] == " " and djtext[index+1]==" "):
      analyzed = analyzed + char
print(analyzed)

I want the output like this我想要这样的 output

god is great神是伟大的

But it gave me this output但它给了我这个 output

godis gre at神是伟大的

You can achieve the result you want by using split to split the string on two spaces and then join the parts again with the spaces removed您可以通过使用split将字符串拆分为两个空格,然后在删除空格的情况下再次join这些部分来获得所需的结果

' '.join(word.replace(' ', '') for word in djtext.split('  ') if word)

Consider this alternative solution using regular expressions:考虑使用正则表达式的替代解决方案:

import re
djtext = "g o d  i s   gre at"
analyzed = re.sub(r' (.)', lambda x: x.group(1), djtext)
print(analyzed)

This matches a space followed by any character , and replaces all such sequences with just the character that was matched.这匹配一个空格后跟任何字符,并仅用匹配的字符替换所有此类序列。

This gives the desired output:这给出了所需的 output:

god is great神是伟大的

If you want to stick with your original approach, then you need to add an extra condition to make it work.如果你想坚持原来的方法,那么你需要添加一个额外的条件来使它工作。 Your original code covers one cases ( reducing multiple spaces) but misses the other cases ( removing the unnecessary spaces).您的原始代码涵盖了一种情况(减少了多个空格),但错过了其他情况(删除了不必要的空格)。

The following version is the correct version of your code.以下版本是您的代码的正确版本。 It adds the condition char == " " and djtext[index - 1] != " " , which just checks that if the current character is a space, the character before it is not also a space.它添加了条件char == " " and djtext[index - 1] != " " ,它只是检查当前字符是否是空格,它之前的字符不是空格。 In such a case, you wouldn't want to keep the space.在这种情况下,您不想保留空间。

djtext = "g o d  i s   gre at"
analyzed = ""
for index, char in enumerate(djtext):
    if not((char == " " and djtext[index + 1] == " ") or (char == " " and djtext[index - 1] != " ")):
        analyzed += char
print(analyzed)

Side note: for readability, I've switched djtext[index] to char and analyzed = analyzed + char to analyzed += char .旁注:为了可读性,我已将djtext[index]切换为char并将analyzed = analyzed + char切换为analyzed += char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM