简体   繁体   中英

How to save each letter while the while loop is running

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:

This is where I am having a problem. I need to save each letter before the vowel(or g as I have attempted). This is the beginnings of a pig latin translator. In this stage, I am trying to flip the prefix and the rest of the word.

    g = word[i]
    i = i+1


prefix = g + word1

print prefix

Example:

input -  person
output - rsonpe

input -  hello
output - llohe

input -  pppat
output - tpppa

input -  hhhhhelllllloool
output - llllllooolhhhhhe

I am flipping the letters before the first vowel, and the rest of the word.

Looks like a job for regular expressions :

import re

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

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

flipper( 'hello' )

output:

'llohe'

Alternatively, if you really want to do it with a while loop, you just need to define a global variable outside of the while loop that you can save to.

you can use regular expression if you are familiar with it or you can just edit your code like this in a very simple and crude way.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM