[英]How do I make my code capitalize the first letter of the word that has a capital letter in it? (Pig Latin)
My code so far is:到目前为止我的代码是:
def to_pig(string):
words = string.split()
for i, word in enumerate(words):
'''
if first letter is a vowel
'''
if word[0] in 'aeiou':
words[i] = words[i]+ "yay"
elif word[0] in 'AEIOU':
words[i] = words[i]+ "yay"
else:
'''
else get vowel position and postfix all the consonants
present before that vowel to the end of the word along with "ay"
'''
has_vowel = False
for j, letter in enumerate(word):
if letter in 'aeiou':
words[i] = word[j:] + word[:j] + "ay"
has_vowel = True
break
#if the word doesn't have any vowel then simply postfix "ay"
if(has_vowel == False):
words[i] = words[i]+ "ay"
pig_latin = ' '.join(words)
return pig_latin
My code right now coverts a string to pig latin string.我的代码现在将字符串转换为 pig 拉丁字符串。 If a word starts with one or more consonants followed by a vowel, the consonants up to but not including the first vowel are moved to the end of the word and "ay" is added.如果一个单词以一个或多个辅音字母开头,后跟一个元音字母,则将不包括第一个元音字母的辅音字母移动到单词的末尾,并添加“ay”。 If a word begins with a vowel, then "yay" is added to the end.如果单词以元音开头,则在末尾添加“yay”。
String: "The rain in Spain stays mainly in the plains"字符串:“西班牙的雨主要集中在平原”
However, my code returns: "eThay ainray inyay ainSpay aysstay ainlymay inyay ethay ainsplay"但是,我的代码返回:“eThay ainray inyay ainSpay aysstay ainlymay inyay ethay ainsplay”
While it should return: "Ethay ainray inyay Ainspay aysstay ainlymay inyay ethay ainsplay"虽然它应该返回:“Ethay ainray inyay Ainspay aysstay ainlymay inyay ethay ainsplay”
How do I fix my code so that it returns the first letter capital for the word that has a capital letter?如何修复我的代码,以便它为具有大写字母的单词返回首字母大写?
Use any(... isupper())
to check for the presence of a capital letter and str.title()
to capitalize the first letter.使用any(... isupper())
检查是否存在大写字母,并str.title()
将第一个字母大写。
>>> words = "eThay ainray inyay ainSpay aysstay ainlymay inyay ethay ainsplay".split()
>>> words = [word.title() if any(c.isupper() for c in word) else word for word in words]
>>> ' '.join(words)
'Ethay ainray inyay Ainspay aysstay ainlymay inyay ethay ainsplay'
A one-line solution would be to check whether the word contains a capital letter.一种单行解决方案是检查单词是否包含大写字母。 If so, you want to convert the capital letter to a lowercase letter and then capitalize the first letter of that word.如果是这样,您想将大写字母转换为小写字母,然后将该单词的第一个字母大写。 You could do that as such.你可以这样做。 Suppose you have your array of words, then:假设你有你的单词数组,那么:
words = [i[0].upper() + i[1:].lower() if i.lower() != i else i for i in words]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.