print results of while loop on the same line [duplicate] - python

This question already has answers here:
Print in one line dynamically [duplicate]
(22 answers)
Closed 8 years ago.
So I am writing a program that asks for your input, puts the words of the sentence you entered into a list and makes the words in the statement go trough the while loop one by one.
The while loops works as follows:
if the first letter of a word is a Vowel it print the word + hay.
Ifthe first letter of the word is not a vowel it puts the first letter of the word at the end of the word + ay
the code:
VOWELS = ['a','e','i','o','u']
def pig_latin(phrase):
#We make sure the input is changed in only lower case letters.
#The words in your sentence are also putted into a list
lowercase_phrase = phrase.lower()
word_list = lowercase_phrase.split()
print word_list
x = 0
while x < len(word_list):
word = word_list[x]
if word[0] in VOWELS:
print word + 'hay'
else:
print word[1:] + word[0] + 'ay'
x = x+1
pig_latin(raw_input('Enter the sentence you want to translate to Pig Latin, do not use punctation and numbers please.'))
My problem:
If i enter for example: "Hello my name is John" in the_raw input at the end of the code i will get the following output:
ellohay
ymay
amenay
ishay
ohnjay
But i actually want the following output:
ellohay ymay amenay ishay ohnjay
If someone could explain me how to achieve this output it would be appriciated

Save the new words in another list, then at the end:
print(" ".join(pig_latin_words))
Example:
VOWELS = {'a','e','i','o','u'}
def pig_latin(phrase):
#We make sure the input is changed in only lower case letters.
#The words in your sentence are also putted into a list
word_list = phrase.lower().split()
print(word_list)
pig_latin_words = []
for word in word_list:
if word[0] in VOWELS:
pig_latin_words.append(word + "hay")
else:
pig_latin_words.append(word[1:] + word[0] + "ay")
pig_latin_phrase = " ".join(pig_latin_words)
print(pig_latin_phrase)
return pig_latin_phrase

Append a comma (,) at the end of your print statements to avoid the newline:
while x < len(word_list):
word = word_list[x]
if word[0] in VOWELS:
print word + 'hay',
else:
print word[1:] + word[0] + 'ay',
x = x+1

Related

How to take non alpha characters out of a string and put them back into the string in the same order?

I'm trying to make a Pig Latin translator, but I have an issue with my code where it doesn't work properly when a word such as "hi" or /chair/ is input. This is because I need my code to detect that the input has a non-alpha character, take it out of the string, and put it back in when it's done changing the string. I am struggling to make this, though.
# Pig Latin 11/11/20
#!/usr/bin/env python3
vowels = ("A", "E", "I", "O", "U")
message = input("Input text to be translated to Pig
Latin\n")
message = message.split()
not_alpha = {}
new_message = []
for word in message:
This commented out section is what I tried to solve this problem with, before the word would go through the editing process, it would go through here and remove the non_alpha keys and place them in a dictionary called not_alpha. My thought process was that I would place it in a dictionary with the character as the key, and the index in the string as the value. Then, at the end, I would loop through every letter in word and reconstruct the word with all the non-alpha characters in order.
# for letter in word:
# if not letter.isalpha():
# not_alpha[letter] = word.index(letter)
# word = word
# for k in not_alpha.keys():
# word.replace(k, "")
letter_editing = word[0]
if word.isalpha():
if letter_editing.upper() in vowels:
word += "yay"
else:
letter_editing = word[0:2]
if letter_editing.upper() in vowels:
word = word[1:] + word[0] + "ay"
else:
word = word[2:] + word[0:2] + "ay"
# for letter in word:
# if word.index(letter) in not_alpha.values():
While I am not positive of all the rules of pig latin you need to apply, from what I see you are only applying two:
Rule 1 - First Letter is Consonant - in which case you are moving
the first letter to the end of the word and adding ay.
Rule 2 - First Letter is Vowel - in which case you are simply adding ay to
the end of the word.
Given these 2 rules and the following observations:
The input message is a stream of alphanumeric characters, punctuation characters and white space characters of length L.
the start of a word within the message is delineated by one or more punctuation or whitespace characters preceding the word.
the end of a word is delineated by either a punctuation character, a whitespace character or end of message.
You can accomplish the translation as follows:
from string import whitespace, punctuation
vowels = 'aeiou'
message = "Oh! my what a beautiful day for the fox to jump the fence!"
output = "" #The output buffer
temp_buf = "" #Temp storage for latin add-ons
word_found = False #Flag to identify a word has been found
cp = 0 # Character pointer to letter of interest in message
while cp < len(message):
ch = message[cp]
if whitespace.find(ch) >= 0 or punctuation.find(ch) >= 0:
word_found = False
if temp_buf:
output += temp_buf
temp_buf = ""
output += ch
else:
if word_found:
output += ch
else:
word_found = True
if vowels.find(ch.lower()) >= 0:
temp_buf = "ay"
output += ch
else:
temp_buf += ch + "ay"
cp += 1
if temp_buf:
output += temp_buf
print(output)
I'd implement this using the callback form of re.sub, where you can have a function determine the replacement for the regular expression match.
import re
vowels = "aeiou"
def mangle_word(match):
word = match.group(0)
if word[0].lower() in vowels:
return word + "ay"
return word[1:] + word[0] + "ay"
message = "Oh! my what a beautiful day for the fox to jump 653 fences!"
print(re.sub("[a-z]+", mangle_word, message, flags=re.I))
outputs
Ohay! ymay hatway aay eautifulbay ayday orfay hetay oxfay otay umpjay 653 encesfay!

Python - I need to rearrange a character of a string element in a list

So I have a function that takes a string input and turns it into pig latin.
For all words that begin with consonants (everything except vowels), I have to take the first letter of that word and move it to the back and then add "ay" to the word.
For example "like" would become "ikelay".
In my program, the string input given to me is first split and then each element of that newly created list is checked to see if the first character of that element is either a vowel, a consonant, or otherwise.
def simple_pig_latin(input, sep=" ", end="."):
splitinput = input.split(sep)
for i in splitinput:
if splitinput[splitinput.index(i)][0] in ['a','e','i','o','u']:
splitinput[splitinput.index(i)] = str(i) + "way"
elif splitinput[splitinput.index(i)][0] in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']:
splitinput[splitinput.index(i)] = str(i) + "ay"
else:
continue
finalstring = ' '.join(splitinput)
finalstring = finalstring + end
simple_pig_latin("i like this")
Notice in the elif branch, I am supposed to take the first letter of i and put it at the end of that word and add "ay" to it. Given the input string "i like this" I should turn the second word (since like starts with l, making it a consonant) into 'ikelay' How would I rearrange like so that it became ikel?
I tried to keep your structure while still removing the useless code :
def simple_pig_latin(input_text, sep=" ", end="."):
words = input_text.split(sep)
new_words = []
for word in words:
if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
new_words.append(word + "way")
else:
new_words.append(word[1:] + word[0] + "ay")
finalstring = sep.join(new_words)
finalstring = finalstring + end
return finalstring
print simple_pig_latin("i like this")
# iway ikelay histay.
Notes :
Your function needs to return something
It's probably easier to create a new list than to mutate the original one
if i is already a string, there's no need to call str(i)
i is usually used for an integer between 0 and n-1. Not for words.
word[0] is the first letter of your word
word[k:] is word without the first k letters
to simplify your code, I consider that if the first letter isn't a vowel, it must be a consonant.
I call lower() on the first letter in order to check if 'I' is a vowel.
For your question, you could change your code str(i) + "ay" to i[1:] + i[0] + "ay" in your elif branch.

using a while True loop

Problem 1.
This problem provides practice using a while True loop. Write a function named
twoWords that gets and returns two words from a user. The first word is of a
specified length, and the second word begins with a specified letter.
The function twoWords takes two parameters:
an integer, length, that is the length of the first word and
a character, firstLetter, that is the first letter of the second word.
The second word may begin with either an upper or lower case instance of
firstLetter. The function twoWords should return the two words in a list. Use
a while True loop and a break statement in the implementation of twoWords. The
following is an example of the execution of twoWords:
print(twoWords(4, 'B')):
A 4-letter word please two
A 4-letter word please one
A 4-letter word please four
A word beginning with B please apple
A word beginning with B please pear
A word beginning with B please banana
['four', 'banana']
This is what I have so far, but it keeps asking me the first question over again
even if I have the right word length. What am I doing wrong?
def twoWords(length, firstLetter):
wordLen = input('A 4-letter word please ')
while len(wordLen) != int(length):
wordlen = input('A 4-letter word please ')
word = input('A word beginning with ' + firstLetter + ' please ')
while word[0] != firstLetter:
word = input('A word beginning with ' + firstLetter + ' please ')
return[wordLen, word]
def twoWords(length,firstLetter):
firstWord = ""
secondWord= ""
while True:
firstWord = input('A ' + str(length) + '-letter word please.')
if length == len(firstWord):
break
while True:
secondWord = input('A word beginning with ' + firstLetter+ ' please')
if secondWord[0] == firstLetter.upper() or secondWord[0] == firstLetter.lower():
break
return [firstWord,secondWord]
print(twoWords(4,'B'))
def twoWord(length, firstLetter):
while True:
word1=(input("Enter a "+ str(length)+"-letter word please:"))
if len(word1)==int(length):
break
while True:
word2=input("Please enter the word beginning with "+firstLetter+" please:")
if word2[0].upper()==firstLetter or word2[0].lower()==firstLetter:
break
return word1, word2
print(twoWord(5, 'b'))

How can I create a code that translates a string sentence to Pyglatin? [duplicate]

This question already has answers here:
python pig latin converter
(2 answers)
Closed 6 years ago.
I have a python code to translate a one worded string to pyglatin and is as follows:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original)>0 and original.isalpha():
word = original.lower()
first = word[0]
rest = word[1:]
new_word = rest+first+pyg
print new_word
However, I'm stumped on how to translate an entire sentence to Pyglatin. The problem I'm working on has these following conditions: for words that begin with consonants, all initial consonants are moved to the end of the word and 'ay' is appended. For words that begin with a vowel, the initial vowel remains, but 'way' is added to the end of the word.
As an example, the string 'How are you today?' would be 'owhay areway uoyay odaytay?'
Read in a sentence. Break it into individual words (split method). Translate each word to Pig Latin. Concatenate the translations.
Does that get you moving?
Try this. Use split and put it into an empty string.
original = raw_input("Enter Sentence: ")
conversion = ""
for word in original.split():
if len(word)>0 and word.isalpha():
word = word.lower()
first = word[0]
rest = word[1:]
pyg = "ay"
pygword = rest+first+pyg
conversion += pygword + " "
print conversion
Here is my try, but if you are not doing it yourself at least try to understand it. (You are free to ask of course)
This has basic ability to deal with special characters like the "?"
def pygword(word):
vowels = 'aeiou'
if word[0] in vowels:
return word + 'way'
else:
while word[0] not in vowels:
word = word[1:]+word[0]
return word + "ay"
def pygsentence(sentence):
final = ''
for word in sentence.lower().split(): #split the sentence
#words should only end in symols in correct grammar
if word[-1] in '.,;:!?':
symbol = word[-1]
word = word[:-1]
else:
symbol = ''
if word.isalpha(): #check if word is alphanumerically
final += pygword(word)+symbol+' '
else:
return "There is a strange thing in one of your words."
return final[:-1] #remove last unecessary space
There may be faster, more robust, simpler, better understandable ways to do this, but this how I would start.
Test yields me:
In[1]: pygsentence("How are you today? I am fine, thank you very much good sir!")
Out[1]: 'owhay areway ouyay odaytay? iway amway inefay, ankthay ouyay eryvay uchmay oodgay irsay!'
Your code does not obey the vowel/consonant rule, so I did my own converter for single words.
Just realized that it won't be able to deal with apastrophes in the middle of words (we don't really have theese in german ;) ) so there is a little task left for you.
edit: I did not know in which order you wanted the consonants apended, since that became not clear from your example. So i made an alternative pygword function:
def pygword2(word):
vowels = 'aeiou'
if word[0] in vowels:
return word + 'way'
else:
startcons = ''
while word[0] not in vowels:
startcons = word[0] +startcons
word = word[1:]
word = word+startcons
return word + "ay"
See the differnece:
In[48]: pygword("street")
Out[48]: 'eetstray'
In[49]: pygword2("street")
Out[49]: 'eetrtsay'

PigLatin translator for words starting with multiple consonants[Python]

VOWELS = ('a', 'e', 'i', 'o', 'u')
def pigLatin(word):
first_letter = word[0]
if first_letter in VOWELS: # if word starts with a vowel...
return word + "hay" # then keep it as it is and add hay to the end
else:
return word[1:] + word[0] + "ay"
def findFirstVowel(word):
novowel = False
if novowel == False:
for c in word:
if c in VOWELS:
return c
I need to write a piglatin translator that can handle words that start with multiple consonants.
For example, the output I get currently when I enter "string" is:
PigLatin("string") = tringsay
I would want the output:
PigLatin("string") = ingstray
To write this, I wrote an additional function to iterate through the word and find the first vowel, but after that I am not sure how to proceed.
Any help would be appreciated.
After finding the first vowel, get its index in the string by doing word.index(c). Then, slice the whole word from the beginning to the index of the vowel
With that slice, put it at the end of the word and add 'ay', as you did in your first function.
You need to find the index of a consonant and slice on it.
Here's an example:
def isvowel(letter): return letter.lower() in "aeiou"
def pigLatin(word):
if isvowel(word[0]): # if word starts with a vowel...
return word + "hay" # then keep it as it is and add hay to the end
else:
first_vowel_position = get_first_vowel_position(word)
return word[first_vowel_position:] + word[:first_vowel_position] + "ay"
def get_first_vowel_position(word):
for position, letter in enumerate(word):
if isvowel(letter):
return position
return -1
There are probably more eloquent ways of doing this but this is my solution. Hopefully it helps!
def pigLatin(aString):
index = 0
stringLength = len(aString)
consonants = ''
# if aString starts with a vowel then just add 'way' to the end
if isVowel(aString[index]):
return aString + 'way'
else:
# the first letter is added to the list of consonants
consonants += aString[index]
index += 1
# if the next character of aString is a vowel, then from the index
# of the vowel onwards + any consonants + 'ay' is returned
while index < stringLength:
if isVowel(aString[index]):
return aString[index:stringLength] + consonants + 'ay'
else:
consonants += aString[index]
index += 1
return 'This word does contain any vowels.'
def isVowel(character):
vowels = 'aeiou'
return character in vowels

Categories