0

I've made a program which reverses the given word. It goes like that:

word = input("Type text: ")
x = len(word)
y = x - 1

while y >= 0:
   print(word[y])
   y -= 1

Naturally loop prints each letter in separate line and I have no idea how to combine those letters into one string. Could you help me?

Georgy
  • 12,464
  • 7
  • 65
  • 73
malpa222
  • 43
  • 1
  • 5

5 Answers5

1

Use word[::-1] to reverse the string. This uses python's list slice method to step through the string with a step of -1.

Prof
  • 657
  • 1
  • 14
  • 24
  • Thanks, that will save me a lot of effort in the future. – malpa222 Jul 12 '18 at 23:29
  • 1
    @DanielLewandowski If you code something in python for a relatively simple task and end up feeling like there might be a better way to do it - don't be afraid to Google what you're trying to do to see if that way exists – Prof Jul 12 '18 at 23:31
0

add a comma after the print

print(word[y]),
Papershine
  • 4,995
  • 2
  • 24
  • 48
Pat Zhang
  • 11
  • 2
0

Another way to do it:

reversed = ''.join([word[len(word) - count] for count in range(1,len(word)+1)])

(replace range with xrange for Python 2)

OregonJim
  • 326
  • 2
  • 10
0

Store it in a list and then use join. Like this:

word = input("Type text: ")
x = len(word)
y = x - 1
store_1 = []
while y >= 0:
   store_1.append(word[y])
   y -= 1
together = ''.join(store_1)
print(together)
Mahir Islam
  • 1,941
  • 2
  • 12
  • 33
0

There is many way to revers the string in your code whatever you done is correct but, in print command if you are using python 3 you have to write this

print(word[y], end="")  
# if you are using python 2 then,
# print word,
# you can also try this 
word = (input("Enter String"))[::-1] # if input is abcd 
print(word) # output is dcba
Om trivedi
  • 32
  • 3