简体   繁体   English

为什么此代码不向后打印字符

[英]Why does this code not print the characters backwards

def anti_vowel(text):
    p=''
    for c in text:
        if c=='a' or c=='A':
            break
        elif c=='e' or c=='E':
            break
        elif c=='i' or c=='I':
            break
        elif c=='o' or c=='O':
            break

        elif c=='u' or c=='U':
            break
        else:
            p=p+c



print(anti_vowel('Hello you'))

You forgot to return p at the end of your function: 您忘记在函数末尾返回 p

def anti_vowel(text):
    p=''
    for c in text:
        if c=='a' or c=='A':
            break
        elif c=='e' or c=='E':
            break
        elif c=='i' or c=='I':
            break
        elif c=='o' or c=='O':
            break
        elif c=='u' or c=='U':
            break
        else:
            p=p+c
    return p

Without that last line all you'll ever print is None , the default return value for functions without an explicit return statement. 没有最后一行,您将要打印的全部是None ,这是None显式return语句的函数的默认返回值。

Of course, your function will only ever print the first consonants, as break ends the loop as soon as you find any vowels. 当然,您的函数只会打印第一个辅音,因为只要找到任何元音, break 终止循环。 It'll not reverse the string, ever. 永远不会反转字符串。 For your sample input, the function return 'H' , because the next letter in the input is a vowel, and break then ends the loop. 对于您的示例输入,该函数返回'H' ,因为输入中的下一个字母是元音,先break然后结束循环。

You could easily re-write your function to use str.lower() and a containment test: 您可以轻松地重新编写函数以使用str.lower()和包含测试:

def anti_vowel(text):
    p = ''
    for c in text:
        if c.lower() in 'aeiou':
            break
        p += c
    return p

This does the same thing, return the first consonants ( 'H' for your sample input). 这样做是相同的,返回第一个辅音(样本输入为'H' )。

If you wanted to reverse letters, and exclude vowels, don't use break and invert where you place the remaining letters. 如果要反转字母排除元音,请不要使用break和invert来放置剩余字母。 You could use continue instead, or more simply, just invert the if test and only process a chararter if it is not a vowel: 您可以改为使用continue ,或更简单地说,只需反转if测试,并且仅在字符不是元音的情况下处理chararter:

def anti_vowel(text):
    p = ''
    for c in text:
        if c.lower() not in 'aeiou':
            p = c + p
    return p

Now consonants are placed before any preceding consonants, reversing the text: 现在,将辅音放在任何前面的辅音之前 ,将文本反转:

>>> def anti_vowel(text):
...     p = ''
...     for c in text:
...         if c.lower() not in 'aeiou':
...             p = c + p
...     return p
... 
>>> anti_vowel('Hello you')
'y llH'

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

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