I'm trying to reverse the words of a multiline string in my program. I want to return a reversed multiline string through my function. However, my function only returns the last line of the string, and not the full string. It works with a print statement inside function, but I don't want to use print as I have call this function further and need the return value.
Asked
Active
Viewed 191 times
0
-
You must join the reverted strings and only then return. – DYZ Oct 16 '20 at 22:24
3 Answers
1
Try this:
song = ("Find light in the beautiful sea, I choose to be happy\n"
"You and I, you and I, we're like diamonds in the sky\n"
"You're a shooting star I see, a vision of ecstasy\n"
"When you hold me, I'm alive\n"
"We're like diamonds in the sky")
for l in [' '.join(l.split()[::-1]) for l in song.split("\n")]:
print(l)
Output:
happy be to choose I sea, beautiful the in light Find
sky the in diamonds like we're I, and you I, and You
ecstasy of vision a see, I star shooting a You're
alive I'm me, hold you When
sky the in diamonds like We're
Or a one-liner:
song = ("Find light in the beautiful sea, I choose to be happy\n"
"You and I, you and I, we're like diamonds in the sky\n"
"You're a shooting star I see, a vision of ecstasy\n"
"When you hold me, I'm alive\n"
"We're like diamonds in the sky")
print('\n'.join(' '.join(l.split()[::-1]) for l in song.split("\n")))
With return
:
song = ("Find light in the beautiful sea, I choose to be happy\n"
"You and I, you and I, we're like diamonds in the sky\n"
"You're a shooting star I see, a vision of ecstasy\n"
"When you hold me, I'm alive\n"
"We're like diamonds in the sky")
def reverse_song(song):
return '\n'.join(' '.join(l.split()[::-1]) for l in song.split("\n"))

baduker
- 19,152
- 9
- 33
- 56
0
song = ("Find light in the beautiful sea, I choose to be happy\n"
"You and I, you and I, we're like diamonds in the sky\n"
"You're a shooting star I see, a vision of ecstasy\n"
"When you hold me, I'm alive\n"
"We're like diamonds in the sky")
def reverse_string(song):
reverse_song = ''
new_list = song.split("\n")
for item in new_list:
item = (item.split(' ')[::-1])
reverse_song = reverse_song + ' '.join(item) + '\n'
return reverse_song
print(reverse_string(song))

Aaj Kaal
- 1,205
- 1
- 9
- 8
-2
song = ("Find light in the beautiful sea, I choose to be happy\n"
"You and I, you and I, we're like diamonds in the sky\n"
"You're a shooting star I see, a vision of ecstasy\n"
"When you hold me, I'm alive\n"
"We're like diamonds in the sky")
def reverse_string(song):
new_list = song.split("\n")
reverse_song = []
for item in new_list:
item = (item.split(' ')[::-1])
reverse_song.append(' '.join(item))
return '\n'.join(reverse_song)
print(reverse_string(song))

Kris
- 518
- 3
- 13
-
This will only return the last item in the list, as `reverse_song` is recreated each iteration. – rcriii Oct 16 '20 at 22:27
-
-
-
-