问题:猪拉丁语是这样的代码:-
My Approach:我已经弄清楚了第一部分,但是当第一个字母被大写时,代码是非常错误的,它不会使用相同的格式。应该发生的是,新的第一个字母将被大写,但事实并非如此(例如: Test -> Esttay)。
我尝试使用if语句嵌套word.capitalize()的条件,但是它没有工作,并将其与else语句混淆。我也尝试过创建一个单独的列表,而所有的时候,计算机被它弄糊涂了。
这是我的密码:
sentence = input ("Type in your sentence here ")
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
for word in sentence.split():
first_letter = word [0]
if first_letter in consonants :
pig = word [1:] + first_letter + "ay"
else :
pig = word + "ay"
for word in sentence.split():
if word.islower() == "false":
print (pig.iscapitalize())
else :
print (pig)预期的结果是,代码可以自动调整正确的位置(Test -> Esttay),但是对于辅音来说,它将被视为元音(Test -> Testay)。
谢谢你对我的照顾
发布于 2019-06-21 13:40:55
主要的问题似乎是word.islower() == "false",它永远不会是真的。相反,检查word.islower() == False,或者更确切地说是not word.islower(),或者word.istitle()。而且,iscapitalize()应该是capitalize(),而第二个for循环似乎毫无用处(无论它是在第一个循环内还是在它之后,从问题的缩进中还不清楚)。
这应该是可行的:
for word in sentence.split():
first_letter = word[0]
if first_letter in consonants:
pig = word[1:] + first_letter + "ay"
else:
pig = word + "ay"
if word.istitle():
print(pig.capitalize())
else:
print(pig)或者更短,使用三元... if ... else ...语句:
for word in sentence.split():
pig = (word[1:] + word[0] if word[0] in consonants else word) + "ay"
print(pig.capitalize() if word.istitle() else pig)发布于 2019-06-21 13:41:05
固定的解决方案,清理您的代码,并使其更有效率。参见代码中的注释。
sentence = input ("Type in your sentence here ")
#Use "not a vowel" instead of "is a consonant".
vowels = ['a','e','i','o','u']
#Iterating through words of sentence
for word in sentence.split():
first_letter = word[0]
#Now you don't have to type out all the consonants
if first_letter not in vowels:
pig = word [1:] + first_letter + "ay"
else:
pig = word + "ay"
#No need for second loop, you're already iterating through each word in the sentence.
#end=" " prints out a sentence instead of individual lines.
if not pig.islower():
pig = pig.title()
print(pig, end=" ")资源:
发布于 2019-06-21 14:23:47
以下是我解决的几个问题:
sentence = input ("Type in your sentence here ")
consonants2 = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
# comment the below 3 lines if you don't need to change format for words which starts with capital consonant letter. I
# I added it because of your example Testay and Esstay which somehow suggest me that you want that.
for i in consonants2:
consonants.append(i.capitalize())
for word in sentence.split():
first_letter = word[0]
if first_letter in consonants :
pig = word [1:] + first_letter + "ay"
else :
pig = word + "ay"
if pig[0].islower():
print(pig.capitalize())
else:
print(pig)
https://stackoverflow.com/questions/56704394
复制相似问题