Skip to content
Advertisement

How to reverse an int in python?

I’m creating a python script which prints out the whole song of ’99 bottles of beer’, but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.

This is my full script,

def reverse(str):
   return str[::-1]

def plural(word, b):
    if b != 1:
        return word + 's'
    else:
        return word

def line(b, ending):
    print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)

for i in range(99, 0, -1):
    line(i, "of beer on the wall")
    line(i, "of beer"
    print reverse("Take one down, pass it around")
    line(i-1, "of beer on the wall n")

I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.

Advertisement

Answer

You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?

def line(bottles, ending):
    return "{0} {1} {2}".format(bottles, 
                                plural("bottle", bottles), 
                                ending)

Which runs like:

>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'

Then pass the result to reverse:

>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'

This makes it much easier to test each part of the code separately and see what’s going on when you put it all together.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement