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
要检查字符串是否都是字母,可以使用
str.isalpha
。要检查是否包含元音,可以使用any
中的生成器表达式来确认至少有一个字母是元音。最后,您可以使用join
中的另一个生成器表达式将元音转换为大写,然后返回一个新字符串。你知道吗示例
为了给出一种不同的方法,除了CoryKramer所回答的以外,还可以使用python
re
模块:我觉得这个更简洁。你知道吗
相关问题 更多 >
编程相关推荐