Reputation: 63
I created my own function to reverse the words in a phrase such as:
reverse("Hello my name is Bob")
Bob is name my Hello
This is the code that I have
def first_word(string):
first_space_pos = string.find(" ")
word = string[0:first_space_pos]
return word
def last_words(string):
first_space_pos = string.find(" ")
words = string[first_space_pos+1:]
return words
def reverse(string):
words = string.count(" ") +1
count = 1
string_reversed = ""
while count <= words:
string_reversed = first_word(string) + str(" ") + string_reversed
string = last_words(string)
count += 1
return string_reversed
Whenever I enter a string, the last letter of the first word of the phrase always gets cut off
reverse("Hello my name is Bob")
Bob is name my Hell
The "o" is missing in Hello. Where did I go wrong?
Upvotes: 2
Views: 158
Reputation: 6233
Your issue is with this code:
def first_word(string):
first_space_pos = string.find(" ")
word = string[0:first_space_pos]
return word
When you get to the iteration of your loop in the reverse
function, you are sending a string without any spaces (because your string consists of the final word to be processed), so string.find(" ")
is returning -1
. Easiest solution is to replace it with the below:
def first_word(string):
first_space_pos = string.find(" ")
if first_space_pos == -1:
first_space_pos = len(string)
word = string[0:first_space_pos]
return word
(This is assuming that you have to modify and use the functions above - other answers provide better ways to implement the functionality)
Upvotes: 1
Reputation: 8018
you need to modify your loop slightly
def reverse(string):
words = string.count(" ") +1
count = 1
string_reversed = ""
while count < words:
string_reversed = first_word(string) + str(" ") + string_reversed
string = last_words(string)
count += 1
print(string + " " + string_reversed)
return string + " " + string_reversed
Upvotes: 1
Reputation: 4670
Although you can use [::-1] to get a reversed list, you can also use reversed
, cause it's more readable and explicit.
>>> words = "Hello my name is Bob"
>>> ' '.join(reversed(words.split(' ')))
'Bob is name my Hello'
Upvotes: 2
Reputation: 174786
Keep it simple,
>>> ' '.join("Hello my name is Bob".split()[::-1])
'Bob is name my Hello'
OR
>>> l = "Hello my name is Bob".split()[::-1]
>>> s = ""
>>> for i,j in enumerate(l):
if i != 0:
s += ' ' + j
else:
s += j
>>> s
'Bob is name my Hello'
>>>
Upvotes: 1