[英]How do I make my code capitalize the first letter of the word that has a capital letter in it? (Pig Latin)
到目前為止我的代碼是:
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
我的代碼現在將字符串轉換為 pig 拉丁字符串。 如果一個單詞以一個或多個輔音字母開頭,后跟一個元音字母,則將不包括第一個元音字母的輔音字母移動到單詞的末尾,並添加“ay”。 如果單詞以元音開頭,則在末尾添加“yay”。
字符串:“西班牙的雨主要集中在平原”
但是,我的代碼返回:“eThay ainray inyay ainSpay aysstay ainlymay inyay ethay ainsplay”
雖然它應該返回:“Ethay ainray inyay Ainspay aysstay ainlymay inyay ethay ainsplay”
如何修復我的代碼,以便它為具有大寫字母的單詞返回首字母大寫?
使用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'
一種單行解決方案是檢查單詞是否包含大寫字母。 如果是這樣,您想將大寫字母轉換為小寫字母,然后將該單詞的第一個字母大寫。 你可以這樣做。 假設你有你的單詞數組,那么:
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.