-1

This is my loop:

hi = 567
z = len(str(hi))
his = str(hi)
for i in range(z - 1, -1 ,-1):
    x = his[i],
    print x,

What I get is:

('7',) ('6',) ('5',)

Is there a way to get it like this:

765

Thank You!

martineau
  • 112,593
  • 23
  • 157
  • 280
  • 1
    should the result be an integer or a string? Or is printing it the important part, no matter what the type? – MSeifert Mar 04 '17 at 21:09

3 Answers3

2

Try this:

print int(str(hi)[::-1])

EDIT: Some performance benchmark compared to the reversed and join solution:

Without int conversion:

>>> timeit.timeit("str(hi)[::-1]", setup='hi=567')
0.33620285987854004
>>> timeit.timeit("''.join(reversed(str(hi)))", setup='hi=567')
0.8570940494537354

With int conversion:

>>> timeit.timeit('int(str(hi)[::-1])', setup='hi=567')
0.6945221424102783
>>> timeit.timeit("int(''.join(reversed(str(hi))))", setup='hi=567')
1.2800707817077637
Szabolcs
  • 3,730
  • 14
  • 34
1

Just use ''.join and reversed:

>>> ''.join(reversed(str(hi)))
'765'
MSeifert
  • 133,177
  • 32
  • 312
  • 322
0

you have an extra comma on the 5th line. change your code to this

hi = 567
z = len(str(hi))
his = str(hi)
for i in range(z - 1, -1 ,-1):
    x = his[i]
    print x,
DorElias
  • 2,158
  • 12
  • 17