python3//如果字符串不包含元音,则打印错误

2024-04-24 00:42:52 发布

您现在位置:Python中文网/ 问答频道 /正文

Write a function which takes a string argument with no spaces in it, searches for vowels (the letters "a", "e", "i", "o", "u") in the string, replaces them by upper case characters, and prints out the new string with the upper cases as well as returns the new string from the function. You should verify it is a string argument using isalpha (so no spaces are allowed!) and return with an error if not (the error message should being with "Error:").

For instance, if the string input is "miscellaneous", then your program will print out and return "mIscEllAnEOUs". If nothing in the string is a vowel, print "Nothing to convert!" and return None.

这是我目前为止所做的工作,但我对作业中粗体部分有困难。你知道吗

def uppercase(word):
    vowels = "aeiou"
    error_msg = "Error: not a string."
    nothing_msg = "Nothing to convert!"  


    new_word = []

    for letter in word:

        if word.isalpha():
            if letter in vowels:
                new_word.append(letter.upper())

            else:
                new_word.append(letter.lower())

        else:
            print(error_msg)
            return None

    new_word = ''.join(new_word)
    return new_word

Tags: andtheinnewstringreturnifis
2条回答

要检查字符串是否都是字母,可以使用str.isalpha。要检查是否包含元音,可以使用any中的生成器表达式来确认至少有一个字母是元音。最后,您可以使用join中的另一个生成器表达式将元音转换为大写,然后返回一个新字符串。你知道吗

def uppercase(word):
    if not word.isalpha():
        return 'Error'
    if not any(letter in 'aeiou' for letter in word):
        return 'Nothing to convert!'
    return ''.join(letter.upper() if letter in 'aeiou' else letter for letter in word)

示例

>>> uppercase('miscellaneous')
'mIscEllAnEOUs'
>>> uppercase('abc123')
'Error'
>>> uppercase('xyz')
'Nothing to convert!'

为了给出一种不同的方法,除了CoryKramer所回答的以外,还可以使用python re模块:

import re

def uppercase(word):
    if not word.isalpha():
        return 'Error'
    if not any(letter in 'aeiou' for letter in word.lower()):
        return 'Nothing to convert!'
    return re.sub(r'[aeiou]', lambda m: m.group().upper(), word)

我觉得这个更简洁。你知道吗

相关问题 更多 >