1

例如,如果我输入bob,它应该给我obb. 同样,类似的东西plank应该给我ankpl

s = input("What word do you want translated?")
first = s[0]
vowel = "aeiou"
for i in range (1, len(s)):
     if first in vowel:
        s = s + "way"
        print (s)
else:
        s = s[1:] + s[0]
        print (s)

这目前只给我lankpfor plank. 谢谢!

4

5 回答 5

4

它实际上可以变得更简单:

s = raw_input("What word do you want translated?").strip()
vowel = set("aeiou")
if vowel & set(s):
    while s[0] not in vowel:
        s = s[1:] + s[0]
    print s
else:
    print "Input has no vowels"
于 2013-11-07T05:29:07.563 回答
1

您只设置first = s[0]一次,并且在循环之前完成。您可能希望将其设置在 for 循环中。

于 2013-11-07T05:29:43.740 回答
0

您的程序的问题else是 没有缩进到正确的级别,因此您有一个for/else构造而不是if/else.

这是一种更有效的方法。

如果vowels = set("aeiou"),你可以像这样得到第一个元音的位置

next(i for i, j in enumerate(s) if j in vowels)

例如:

>>> s = "plank"
>>> vowels = set("aeiou")
>>> next(i for i, j in enumerate(s) if j in vowels)
2

>>> s[2:] + s[:2]
'ankpl'

所以现在你只需要操作字符串一次。

如果没有元音,代码会引发异常而不是永远运行:)

>>> s="why why why?"
>>> next(i for i, j in enumerate(s) if j in vowels)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
于 2013-11-07T05:42:32.557 回答
0

搜索元音然后将字符串旋转一次可能更有效一些:

vowels = 'aeiou'

for index, character in enumerate(s):
    if character in vowels: break

s = s[index:] + s[:index]
于 2013-11-07T05:51:26.800 回答
0

这将起作用

#Move Consonants to the End
def MoveConsonants(input1):
    contains_vowel = False
    for letter in input1: #Check if the work contains a vowel or not
        if letter in 'aeiou':
            contains_vowel = True
    #If the word doesn't contain a vowel, return the same word
    if not contains_vowel: 
        return input1

    #Check if the first letter is a vowel, if so, we can return the string
    if input1[0] in 'aeiou':
        return input1

    #if the first letter is not a vowel, move the first letter to the end and repeat the process
    input1 = input1[1:] + input1[0]
    return MoveConsonants(input1)
print(MoveConsonants('Plank'))
于 2019-01-08T15:33:27.897 回答