ChubbyBear
ChubbyBear

Reputation: 7

How to get output in one line

I do reverse string and input is The quick brow fox

def reverse_word(word):
    for i in word:
      re = (i[::-1])
      print('Reversed words ==> '+ re )

def main():
    word = input('Enter a line : ').split()
    reverse_word(word)
main()

but my result is

Reversed words ==> ehT
Reversed words ==> kciuq
Reversed words ==> worb
Reversed words ==> xof

I want result like:

Reversed words ==> ehT kciuq worb xof

Upvotes: 0

Views: 296

Answers (5)

Chris
Chris

Reputation: 36660

When you say word it looks like this is really a collection of words, so words is probably a better name, and each of those should probably be word rather than i.

def reverse_words(words):
    for word in words:
      re = (word[::-1])
      print('Reversed words ==> '+ re )

def main():
    words = input('Enter a line : ').split()
    reverse_words(words)

main()

Now, we can use a generator expression to generate the reversed word for each word.

(word[::-1] for word in words)

And let's join those with a space.

' '.join(word[::-1] for word in words)

And putting it into a function, using an f-string to print it:

def reverse_words(words):
    print(f"Reversed words ==> {' '.join(word[::-1] for word in words)}")

Alternatively, we can use reversed.

def reverse_words(words):
    print(f"Reversed words ==> {' '.join(''.join(reversed(word)) for word in words)}")

Upvotes: 0

Shanha_Kim
Shanha_Kim

Reputation: 31

you can use end in print method

def reverse_word(word):
    print('Reversed words ==> ', end='')
    for i in word:
      re = (i[::-1])
      print(re, end=' ' )

def main():
    word = input('Enter a line : ').split()
    reverse_word(word)
main()

Upvotes: 1

seldomspeechless
seldomspeechless

Reputation: 174

def reverse_word(word):
    res = ""
    for i in word:
      re = (i[::-1])
      res += " "+re
    return 'Reversed words ==>'+ res

word = input('Enter a line : ').split()
print(reverse_word(word))

Believe this would have desired effect.

Not really a question asked so no need to explain it further. Keep it simple!

Upvotes: 0

Extorc Productions
Extorc Productions

Reputation: 136

In order to get a single line output , you can have a global string

out = ""

To which you will concatenate your resulting words.

out += " " + re

Inside the for loop And this can be printed right after the end of the loop.

out = ""
def reverse_word(word):
    for i in word:
      re = (i[::-1])
      out += " " + re
    print("Reversed Words ==> " + out)

def main():
    word = input('Enter a line : ').split()
    reverse_word(word)
main()

Upvotes: 0

BeamString
BeamString

Reputation: 361

Can try this one :

def reverse_word(word):
    print("Reversed words ==>", end="")
    for i in word:
        re = (i[::-1])
        print(" " + re, end="")


def main():
    word = input('Enter a line : ').split()
    reverse_word(word)


main()

Upvotes: 0

Related Questions