在for循环中使用字符串连接时的异常行为

时间:2015-04-11 22:04:25

标签: python

因此,下面的代码会正确地从字符串中删除所有元音。

def disemvowel(string):
    # Letters to remove & the new, vowerl free string
    vowels_L = list('aeiouAEIOU')
    new_string = ""

    # Go through each word in the string
    for word in string:

        # Go through each character in the word
        for character in word:

            # Skip over vowels, include everything elses
            if character in vowels_L:
                pass
            else:
                new_string += character

    # Put a space after every word
    new_string += ' '

    # Exclude space place at end of string
    return new_string[:-1]

no_vowels = disemvowel('Nasty Comment: Stack exchange sucks!')
print(no_vowels)

>>>>python remove_vowels.py
>>>>Nsty Cmmnt: Stck xchng scks!

然而,当我移动声明时:" new_string + =' '"在我认为它应该是的地方(我来自C / C ++背景),我最终得到了一个奇怪的答案,

def disemvowel(string):
    # Letters to remove & the new, vowerl free string
    vowels_L = list('aeiouAEIOU')
    new_string = ""

    # Go through each word in the string
    for word in string:

        # Go through each character in the word
        for character in word:

            # Skip over vowels, include everything elses
            if character in vowels_L:
                pass
            else:
                new_string += character

    # THIS IS THE LINE OF CODE THAT WAS MOVED        
    # Put a space after every word
    new_string += ' '

    # Exclude space place at end of string
    return new_string[:-1]

no_vowels = disemvowel('Nasty Comment: Stack exchange sucks!')
print(no_vowels)

>>>>python remove_vowels.py
>>>>N  s t y   C  m m  n t :   S t  c k    x c h  n g    s  c k s !

在单词完成迭代后,不是放置空格,而是在有元音的地方也有空格。我希望有人能够解释为什么会发生这种情况,即使在C中,结果也会大不相同。此外,任何精简/浓缩可能的建议都将受到欢迎! :)

2 个答案:

答案 0 :(得分:8)

for word in string不会迭代这些词;它迭代字符。您根本不需要添加空格,因为原始字符串中的空格会被保留。

答案 1 :(得分:0)

作为interjay评论,你的缩进就是出路。 Python依赖于缩进来描述哪些语句属于哪个块,而不是更常见的BEGIN ... END{ ... }

此外,user2357112 observes您希望字符串中出现,而字符串只是一个字符列表,for word in string将设置word到一个string一个字符

使用not in而不是ifpass一起使用也更加清晰。

这更接近你的意图

def disemvowel(string):

    # Letters to remove & the new, vowel-free string
    vowels_list = 'aeiouAEIOU'
    new_string = ""

    # Go through each character in the string
    for character in string:

        # Skip over vowels, include everything else
        if character not in vowels_list:
            new_string += character

    return new_string


print disemvowel('Nasty Comment: Stack exchange sucks!')

<强>输出

Nsty Cmmnt: Stck xchng scks!