简体   繁体   中英

Python 3 // Printing an error if a string contains no vowels

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 .

This is what I have so far that is working, but I'm having trouble with the part in bold in the assignment.

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

To check that a string is all letters you can use str.isalpha . To check that there are vowels contained, you can use a generator expression within any to confirm that at least one of the letters is a vowel. Then lastly you can do the conversion with another generator expression within join to uppercase only the vowels, then return a new string.

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)

Examples

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

Just to give a different approach, in addition to what CoryKramer answered, you could use a python re module:

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)

I think this is more concise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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