0

I'm pretty new to python and curious why my function prints out each character from a new line. Any suggestions on how to correct it? Any other implementations of that would be helpful as well.

This how my function looks like

def reverse(word):
    len_word = len(word)
    x = 0
    while x < len_word:
        x += 1
        index = len_word - x 
        print(word[index])
reverse("123abcd")

What I get is the input with each character on a new line.

What I want to get: dcba321

sumixam
  • 77
  • 1
  • 8
  • The marked duplicate answers the question you asked. But please also see https://stackoverflow.com/questions/931092/reverse-a-string-in-python for more direct ways to solve the problem. – Karl Knechtel Oct 19 '19 at 01:49

1 Answers1

1

print() adds a newline by default. A general way to deal with this is:

import sys
sys.stdout.write(word[index])

If you're using python3, you can also do:

print(word[index], end='')
Nick Reed
  • 4,989
  • 4
  • 17
  • 37