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])
Related
s = "Some string"
for i in s.split():
print(i)
word += i[::-1]
word += " "
Expected Output:
"emoS gnirts"
Output:
"emoS gnirts "
How can I know if it's the last loop so i can avoid adding a " " to my word?
One way you could know when it's the last loop is by storing the number of words in a variable and then using an if statement to see when the last word hits. Something like this:
s = "Some string"
word=""
count = 0
sLen = len(s.split())
for i in s.split():
print(i)
word += i[::-1]
if not (count == (sLen - 1)):
word += " "
else:
print("last loop")
count += 1
This is just a reference, that'll be the way I will do it:
s = "some string"
word = ' '
word = ' '.join(s[::-1] for s in s.split()) # generator expression and join
Perhaps the shortest and fastest way:
>>> ' '.join(s[::-1].split()[::-1])
'emoS gnirts'
Another alternative;
myString = "Some string"
print(' '.join(''.join(reversed(word)) for word in myString.split()))
emoS gnirts
What I usually do is put an if statement comparing the iterable's length to the iteration number. Like this:
word = ''
s = "Some string"
for e, i in enumerate(s.split()):
print(i)
word += i[::-1]
if not (len(s.split()) - 1) == e:
word += " "
#proof the last character is 's' and not a space
print(word[-1])
You can do it in many ways, but generally, in python, people prefer using the enumerate construction.
s = "Some string"
for index, i in enumerate(s.split()):
print(i)
word += i[::-1]
if index < len(s.split()) - 1:
word += " "
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 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)
def main():
print('Please enter a sentence without spaces and each word has ' + \
'a capital letter.')
sentence = input('Enter your sentence: ')
for ch in sentence:
if ch.isupper():
capital = ch
sentence = sentence.replace(capital, ' ' + capital)
main()
Ex: sentence = 'ExampleSentenceGoesHere'
I need this to print as: Example sentence goes here
as of right now, it prints as: Example Sentence Goes Here (with space at the beginning)
You can iterate over the string character by character and replace every upper case letter with a space and appropriate lower case letter:
>>> s = 'ExampleSentenceGoesHere'
>>> "".join(' ' + i.lower() if i.isupper() else i for i in s).strip().capitalize()
'Example sentence goes here'
Note that check if the string is in upper case is done by isupper(). Calling strip() and capitalize() just helps to deal with the first letter.
Also see relevant threads:
Elegant Python function to convert CamelCase to snake_case?
How to check if a character is upper-case in Python?
You need to convert the each uppercase letter to a lowercase one using capital.lower(). You should also ignore the first letter of the sentence so it stays capitalised and doesn't have a space first. You can do this using a flag as such:
is_first_letter = True
for ch in sentence:
if is_first_letter:
is_first_letter = False
continue
if ch.isupper():
capital = ch
sentence = sentence.replace(capital, ' ' + capital.lower())
I'd probably use re and re.split("[A-Z]", text) but I'm assuming you can't do that because this looks like homework. How about:
def main():
text = input(">>")
newtext = ""
for character in text:
if character.isupper():
ch = " " + character.lower()
else:
ch = character
newtext += ch
text = text[0]+newtext[2:]
You could also do:
transdict = {letter:" "+letter.lower() for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
transtable = str.maketrans(transdict)
text.translate(transtable).strip().capitalize()
But again I think that's outside the scope of the assignment
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.