如何在python中更新字符串长度

2024-09-29 18:34:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让这个while循环从输入单词的前面删除所有辅音,但是它只经过一次就结束了,我如何保持这个while循环一直到所有辅音都在单词的末尾(例如:我希望“switch”是“itch+sw”,而对于它来说,一旦辅音被移动,在末尾添加“ay”以形成“itchsway”,这是我目前的代码,我对Python非常陌生,因此任何帮助都将不胜感激!你知道吗

print("Pig Latin Translator Test!")
name = raw_input("What is your name?")
if len(name) > 0 and name.isalpha():
    print("Hello!")
else:
    print("That's not a name!")
word = raw_input("What is your word?")
word0 = word[0]
word0 = word0.lower()
n = 0
if len(word0) > 0 and word0.isalpha():
    word0proof = word0
else:
    print("That isn't a word!")
if word0proof in "aeiou":
    wordoutput = word + "yay"
    print (wordoutput)
else:
    print("Your word doesn't begin with a vowel")
if word0proof in "bcdefghjklmnpqrstvwxyz":
    word1 = word0proof
else:
    word0proof = word0proof
#Now get word1 to move all consonants to the back of the word and add "ay"

这就是我在代码中遇到的问题

while word1 in "bcdefghjklmnpqrstvwxz":
    word1 = word[n:] + word0 + "ay"
    n = n + 1
    print word1
    word1 = word1

除了所有的缩进问题,我基本上只是偷了一些改进代码的想法,得到了这个(去掉了所有的变量,然后借用了元音列表中提供的while语句)

print("Pig Latin Translator Test!")
name = raw_input("What is your name, friend?")
if len(name) > 0 and name.isalpha():
    print("Hello!")
else:
    print("That's not a name!")
word = raw_input("What is your word?")
VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
if word[0] in VOWELS:
    word = word + "yay"
else:
    while word[0] not in VOWELS:
        word = word[1:] + word[0]
    word = word + "ay"
print (word)

Tags: nameininputrawifiswhatelse
2条回答

正如其他人提到的,你需要修正你的压痕,并可能考虑以不同的方式解决这个问题。你知道吗

要直接回答您的问题:

while word[0].lower() not in "bcdefghjklmnpqrstvwxz":
    word = word[1:] + word[0]
word = word + "ay"

您希望在循环完成后添加"ay",或者最终得到多个"ay"'s

下面是一个集成到简化版代码中的循环示例。你知道吗

VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
word = raw_input("Please enter a word: ")
if word[0] in VOWELS:
    word = word + "ay"
else:
    while word[0] not in Vowels:
        word = word[1:] + word[0]
    word = word + "ay"
print (word)

我在您的代码中看到许多问题: 这是多余的else条件,字符串中也有e

if word0proof in "bcdefghjklmnpqrstvwxyz":
    word1 = word0proof
else:
    word0proof = word0proof

检查首字母是否为元音或辅音的条件可以组合为:

if len(word0) > 0 and word0.isalpha():
    word0proof = word0
    if word0proof in "aeiou":
        wordoutput = word + "yay"
            print (wordoutput)
    elif word0proof in "bcdfghjklmnpqrstvwxyz":
            word1 = word0proof

在你的逻辑中实现你想要的:

while word1 in "bcdefghjklmnpqrstvwxz":
    word1 = word[n:] + word0 + "ay"
    n = n + 1
    print word1
    word1 = word1

当您仍然不知道下一次迭代是否有辅音时,您不必要地将ay赋值为end。我建议您首先找出要删除的字符串的多少部分,然后添加逻辑以附加ay。像这样:

cons_index = -1
for index,letter in enumerate(word):
    if letter not  in "bcdefghjklmnpqrstvwxz":
        cons_index = index
        break
your_word = word[cons_index: ]   + word[: cons_index] + "ay"

也不要使用太多的variables这会使您的代码难以理解,例如,不需要变量word0word0proofword1,您可以简单地作为word[0]访问它们。你知道吗

相关问题 更多 >

    热门问题