0

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.

user863975
  • 15
  • 6

3 Answers3

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