This concise and straight-to-the-point article brings to the table two different ways to reverse the order of digits in a given number (integer or float) in Python.
Using string manipulation
The steps to get the job done are:
- Convert the number to a string using the
str()
function. - Reverse the string using slicing with a step of
-1
, which can be done by using[::-1]
. - If the number was a float, remove the trailing zeros using the
rstrip("0")
method (optional). - Convert the reversed string back to a number using the
int()
orfloat()
function.
Code example:
number = 2023.2024
number_str = str(number)
reversed_str = number_str[::-1].rstrip("0")
reversed_number = int(reversed_str) if reversed_str.isdigit() else float(reversed_str)
print(reversed_number)
# Output: 4202.3202
In case you need to perform this task many times, defining a function is more convenient:
def reverse_number(number):
number_str = str(number)
reversed_str = number_str[::-1].rstrip("0")
reversed_number = int(reversed_str) if reversed_str.isdigit() else float(reversed_str)
return reversed_number
This technique is simple and easy to understand, but it won’t work with negative numbers. This limitation will be eliminated in the following method.
Using mathematical operations
The idea can be explained as shown below:
- Check if the number is negative using the
math.copysign()
function from themath
module. If it is, store the sign for later use. - Take the absolute value of the number using the
abs()
function. - Reverse the number using mathematical operations:
- For integers, use a
while
loop and repeatedly divide the number by10
while updating the reversed number by multiplying it by10
and adding the remainder. - For floats, convert the number to a string, reverse the string, and convert it back to a float.
- For integers, use a
- If the original number was negative, multiply the reversed number by
-1
to restore the sign.
Code example:
import math
# Define a function that takes in a number and reverses it
# This function can handle integers and floats (negative and positive)
def reverse_number(number):
negative = math.copysign(1, number) == -1
number = abs(number)
if isinstance(number, int):
reversed_num = 0
while number > 0:
reversed_num = (reversed_num * 10) + (number % 10)
number //= 10
else: # float
number_str = str(number)
reversed_str = number_str[::-1]
reversed_num = float(reversed_str)
return -reversed_num if negative else reversed_num
# Test it out
print(reverse_number(123))
print(reverse_number(-123))
print(reverse_number(123.45))
print(reverse_number(-123.45))
Output:
321
-321
54.321
-54.321
This method is a bit more complicated, but it overcomes the weakness with negative numbers of the first method.