【问题标题】:How to save each letter while the while loop is running如何在 while 循环运行时保存每个字母
【发布时间】:2015-04-07 01:55:43
【问题描述】:
word = raw_input('Enter a word: ')

for i in word:
    if i in ['a','e','i','u','A','E','I','O','o','U']:
        word1 = i
        break

    else:
        print i,


print ""

i = 0
while word[i]!=word1:

这是我遇到问题的地方。我需要在元音之前保存每个字母(或者我尝试过的 g )。这是猪拉丁语翻译的开端。在这个阶段,我试图翻转前缀和单词的其余部分。

    g = word[i]
    i = i+1


prefix = g + word1

print prefix

例子:

input -  person
output - rsonpe

input -  hello
output - llohe

input -  pppat
output - tpppa

input -  hhhhhelllllloool
output - llllllooolhhhhhe

我正在翻转第一个元音之前的字母,以及单词的其余部分。

【问题讨论】:

  • 你试过追加到列表吗?
  • 不,我可以在哪里使用 .append?
  • 在你的 if 语句中。如果您写出输出的明确详细信息,您希望我可以更具体。
  • 是的,请您说的更具体些。抱歉,我才刚入门。
  • 然后使用示例数据和预期输出更新您的帖子。

标签: python while-loop


【解决方案1】:

如果您熟悉正则表达式,您可以使用它,或者您可以像这样以非常简单粗暴的方式编辑您的代码。

word = raw_input('Enter a word: ')
word1 = 0
for i in range(0,len(word)) :
    if word[i] in ['a','e','i','u','A','E','I','O','o','U']:
        word1=i
        break
print word[word1+1:]+word[:word1]+word[word1]

【讨论】:

  • 感谢您的解决方案,但是有没有办法可以解释最后一行,并将一些元素保存到变量中,以便于阅读?
  • 我只是在最后一行分割字符串。 python 提供了一种非常简单的方法来做到这一点。例如说你有一个字符串wish='hello'来获取任何特定索引中的任何字符你只需要wish [index] ex:-wish [0]会给你'h',如果你只想得到前3个字符串中的字符,您可以只做 wish[:3] ,这将为您提供索引 0 到 3(0,1,2) 的字符,即“hel”。同样的方式 wish[3:] 会给你从 4 到字符串结尾的索引字符。了解有关切片字符串检查的更多信息pythoncentral.io/cutting-and-slicing-strings-in-python
  • 而不是每次都创建一个变量。您只需创建一个列表并附加您要存储的字符即可将您需要的元素保存在一个列表中。
【解决方案2】:

看起来像是regular expressions 的工作:

import re

Vowel = re.compile('[aeiouAEIOU]')

def flipper ( inStr ) :
    myIndex = Vowel.search( inStr ).start() + 1
    return inStr[myIndex:] + inStr[:myIndex]

flipper( 'hello' )

输出:

'llohe'

或者,如果您真的想使用while 循环来实现,您只需要在while 循环之外定义一个可以保存到的全局变量。

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 2019-12-29
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多