sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for i in sentence:
if i.isalpha() == True:
if i[0] in vowels:
print(i + "way")
new = i + "way"
sentence.replace(i, new)
else:
print(i[1:] + i[0] + "ay")
new = i[1:] + i[0] + "ay"
sentence.replace(i, new)
else:
print(i)
print(sentence)
I am trying to make a piglatin sentence converter, I have been able to make the converter print the correct values for the translation, but I cannot make the program change the actual values of the list, which I need it to do so that I can print the converted text like the original, in a string format like "I like rabbits" instead of a list like:
I
like
rabbits
I would like to know how I use the replace() function to change my list inside my for loop and if statements. If there is another way that is better that would be even better.
Thank You.
sentence.replace(i, new) function returns the new string - it doesn't do replacement in-place (on the original string).
You'd want to loop through indexes to easily modify the list being iterated over (you don't change your wheels whilst driving, do you?):
sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for idx in range(len(sentence)):
to_replace = sentence[idx]
if to_replace.isalpha() == True:
if to_replace[0] in vowels:
print(to_replace + "way")
new = i + "way"
else:
print(to_replace[1:] + to_replace[0] + "ay")
new = to_replace[1:] + to_replace[0] + "ay"
sentence[idx] = new
else:
print(to_replace)
print(sentence)
You don't really need to call replace() (which is a string method, not list). You'd assign to sentence[idx] instead.
Your list doesn't have a .replace method but, the str's in the list do.
It looks as though you are wanting to modify your list while iterating through the items.
sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for idx, word in enumerate(sentence):
if word.isalpha() == True:
if word[0] in vowels:
print(word + "way")
new = word + "way"
else:
print(word[1:] + word[0] + "ay")
new = word[1:] + word[0] + "ay"
sentence[idx] = new
else:
print(word)
print(sentence)
The enumerate builtin is especially useful when iterating and modifying items.
Related
The objective of this python exercise is to build a function that turns text into pig latin, a simple text transformation that modifies each word by moving the first character to the end and appending "ay" to the end.
For example, python ends up as ythonpay.
I actually built this script, but I am confused as to why it is not iterating over all text.split elements? And why it is only modifying the last element?
def pig_latin(text):
say = ""
# Separate the text into words
words = text.split()
for word in words:
# Create the pig latin word and add it to the list
new_word = word[1:] + word[0] + "ay"
say = "".join(new_word)
# Turn the list back into a phrase
return say
print(pig_latin("hello how are you"))
# Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun"))
# Should be "rogrammingpay niay ythonpay siay unfay"
This section here is why. You only have one new_word variable, so each time this loop runs, it overwrites the previous value. The only value that doesn't get overwritten is the last one, and you end up with a single string.
for word in words:
new_word = word[1:] + word[0] + "ay"
say = "".join(new_word)
Instead, make sure that each new word ends up in a list. The most intuitive way to do it, IMO, is through list comprehension. Below is how you would format it for this, but look up how to do them. Seriously, it's a couple minutes of your time and they'll be one of your best friends as you continue to learn. You can also do the same thing with dictionaries.
pig_latin_text = [word[1:] + word[0] + "ay" for word in words]
say = " ".join(pig_latin)
def pig_latin(text):
say = ""
words = text.split()
for word in words:
newword = word[1:] + word[0] + 'ay'
say = say + " " + newword
return say
You are iterating over all the words, but you override the value in say in every iteration. Doing say = "".join(new_word) will not combine the new word with the existing value of say, but override it - the join function joins the arguments it receives, and in this case it only received new_word.
To fix it you should replace that line with:
say += " " + new_word
def pig_latin(text):
say = ""
# Separate the text into words
words = text.split()
for word in words:
# Create the pig latin word and add it to the list
new_word = word[1:] + word[0] + "ay"
say = say + " " + "".join(new_word)
# Turn the list back into a phrase
return say
print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
def cat_latin_word(text):
""" convert the string in another form
"""
constant = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
for word in text.split():
if word[0] in constant:
word = (str(word)[-1:] + str(word)[:4] + "eeoow")
else:
word = (str(word) + "eeoow")
print(word)
def main():
""" converts"""
text = input("Enter a sentence ")
cat_latin_word(text)
main()
A few pointers:
Converting your code to "one line" doesn't make it better.
No need to type out all consonants, use the string module and use set for O(1) lookup complexity.
Use formatted string literals (Python 3.6+) for more readable and efficient code.
No need to use str on variables which are already strings.
For a single line, you can use a list comprehension with a ternary statement and ' '.join.
Here's a working example:
from string import ascii_lowercase, ascii_uppercase
def cat_latin_word(text):
consonants = (set(ascii_lowercase) | set(ascii_uppercase)) - set('aeiouAEIOU')
print(' '.join([f'{word}eeow' if not word[0] in consonants else \
f'{word[-1:]}{word[:4]}eeoow' for word in text.split()]))
text = input("Enter a sentence ")
cat_latin_word(text)
You may use a list to put all the words or use print() in a different way.
Example:
print(word, end="\t")
where here I use the keyword argument end to set it to '\t' ( by default is '\n')
Simply edited your code to return the results as a words separated by space.
def cat_latin_word(text):
constant = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
result = []
for word in text.split():
if word[0] in constant:
word = (str(word)[-1:] + str(word)[:4] + "eeoow")
result.append(word)
else:
word = (str(word) + "eeoow")
result.append(word)
return ' '.join(result)
def main():
text = 'ankit jaiswal'
print(cat_latin_word(text))
def convert_pig_latin(pig):
first_letter = pig[0]
#Check if Vowel
if first_letter in 'aeiou':
pig_word = pig + 'ay'
else:
pig_word = pig[1:] + first_letter + 'ay'
print('Pig Latin:',pig_word)
So basically, this only works for 1 single word input. Let's say the user enters a sentence, it won't work which is obvious. This code is in my functions tab, and my main module of course runs it with an input sentence given. Could someone please help me out how it'll take a whole sentence instead of just one word -.- Tried using a for loop but messed it up.
Appreciate it, thanks!
You could use a list comprehension here:
def pig_latin(sentence):
return ' '.join([s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay' for s in sentence.split()])
print(pig_latin("convert all the words"))
Output:
onvertcay allay hetay ordsway
You could also keep your current approach where the function converts a single word, and use map():
>>> def pig_latin_word(s):
... return s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay'
...
>>> ' '.join(map(pig_latin_word, "convert all the words".split()))
'onvertcay allay hetay ordsway'
>>>
Convert the string into a list of strings:
words = pig.split(' ')
Then you would run a for loop on the list:
for word in words:
#run your conversation code on each word
Then join the list back into a string:
pig = ' '.join(words)
Intention is to write a function that would reverse the words in a string. So that if the input is: "I am a student" the output should be "student am a I"
I have the following code in Python which first reverses all the characters in a string and then loops the reversed sentence to reverse the words and prints them to a "final sentence" variable.
Because the condition I am checking for is just a space, the first word doesn't get printed i.e. if the input is " I am a student" my code works (notice the space before "I") ... however if the input is "I am a student" then the output is just "student a am"
I need to know how can I modify my IF statement so it doesn't miss the first word
def reverse(sentence):
count = 0
new_sentence = ''
final_sentence = ''
counter = 0
word = ''
for char in sentence[::-1]:
new_sentence = new_sentence + char
for char in new_sentence:
if char != " ":
count = count + 1
continue
else:
for i in new_sentence[count-1::-1]:
if i != " ":
word = word + i
else:
break
count = count + 1
final_sentence = final_sentence + " " + word
word = ''
print final_sentence
reverse("I am a student")
I'm not sure why you are doing such complicated loops? You can just split the sentence, reverse and then join it again:
>>> ' '.join('I am a student'.split(' ')[::-1])
'student a am I'
To translate that into a function:
def reverse_sentence(sentence):
return ' '.join(sentence.split(' ')[::-1])
You're doing several strange things in your code. For example:
new_sentence = ''
for char in sentence[::-1]:
new_sentence = new_sentence + char
The string you're building through concatenation is already present in sentence[::-1]. You could've just done new_sentence = sentence[::-1].
You can check for the first word by using enumerate() and checking whether there is a space prior to that point in the sentence:
for idx,char in enumerate(new_sentence):
if char != " " or ' ' not in new_sentence[:idx]:
However, the easiest way to accomplish your actual goal is with split(), splitting the sentence by whitespace automatically. Use join() to put it back together once you've reversed it.
def reverse(sentence):
return ' '.join(sentence.split()[::-1])
I'm trying to basically take an inputted sentence and alter each word slightly. This should work for any sentence.
So far I have this:
line = (input("Enter a sentence: "))
words = line.split()
for word in words:
new_line = 'em-' + word[1:] + word[0] + '-ma'
print(new_line)
but all this does is take the last word in the sentence and does what i want it to do. I want each word to be altered where the first letter in each word is moved to the last place, and each word is "sandwiched" by "em-" and "-ma". Any advice?
update:
what if i did this?
line = (input("Enter a sentence: "))
words = line.split( )
for word in words:
print('Result: ','em-' + word[1:] + word[0] + '-ma')
this gives me what I want but it repeats result over and over and the words are in a vertical line. how do i fix this?
new_line is being replaced every time the loop is executed so in the print statement outside of the loop it has the value of the last word.
If you just want to print each word, move the print inside the loop.
If you want all of the words accessible outside of the loop, add them all to a list or replace the loop with a list comprehension:
new_words = ['em-' + word[1:] + word[0] + '-ma' for word in words]