【发布时间】:2016-04-05 16:26:15
【问题描述】:
目前,我的代码的第一部分工作正常。如果它检测到第一个字符(索引 0)是元音,它会停止并在单词末尾添加“yay”。
第二部分旨在捕捉到第一个元音的辅音。这可以正常工作。
当我尝试获取原始单词并将所有内容切掉到第一个元音并从中创建一个新的子字符串时,就会出现问题。这意味着如果用户输入“hello”,它应该输出“ellohay”。我可以得到“hellohay”,但不知道如何捕捉这些初始辅音并将它们切掉。
# Pig Latinify
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']
def pig_latinify():
state = True
while state == True:
user_input = raw_input("Enter a word to be translated: ").lower()
# If the first character in input is a vowel add 'yay' to input and print.
if user_input[0] in vowels[0:]:
print ""
print "Begins with a vowel."
pig_output = user_input + "yay"
print user_input, "becomes:", pig_output
print ""
else:
print ""
print "Doesn't begin with a vowel."
captured_consonants = ""
captured_substring = ""
new_user_input = ""
# Capture the consonants up to the first vowel
for i in user_input:
if i in vowels:
break
if i in consonants:
captured_consonants = captured_consonants + i
# Slice user_input up to the first vowel and create a substring beginng from the first vowel until the end of the string.
if i in consonants:
break
if i in vowels:
captured_substring = captured_substring + i
print captured_substring
# Concatenate substring of user_input with captured_consonants and 'ay'
pig_output = captured_substring + captured_consonants + "ay"
print user_input, "becomes:", pig_output
print ""
pig_latinify()
【问题讨论】:
标签: python python-2.7 slice