Python程序连续将辅音移动到字符串结尾,直到第一个字母是元音

时间:2013-11-07 05:24:29

标签: python string loops

例如,如果我输入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)

目前我只为lankp提供了plank。 谢谢!

5 个答案:

答案 0 :(得分: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"

答案 1 :(得分:1)

您只需设置一次first = s[0]即可在循环之前完成。你可能想在for循环中设置它。

答案 2 :(得分: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

答案 3 :(得分:0)

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

vowels = 'aeiou'

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

s = s[index:] + s[:index]

答案 4 :(得分: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'))