Search code snippets, questions, articles...

Reverse a string or number in python

If you are using Python to develop your application and have a requirement to reverse a string or number then you can use one of the methods explained in this post. Python does not have a built-in function to reverse a string like List so we will have to
#reverse a number
my_num = 12345
reversed_num = str(my_num)[::-1]
print(reversed_num)
# -> 54321

#reverse a string
my_str = "hello"
reversed_str = my_str[::-1]
print(reversed_str)
# -> olleh
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

The above code example shows the fastest way to reverse a Python String or a number. We just pass the [::-1] after the variable name to reverse a string.

Syntax

Variable[::-1]

Reverse a number in Python

We will use the same syntax here that we are using in the above code example to reverse a number in Python. To reverse a number with the same approach, we need to convert it to string type first and after reversing the number we are converting it back to an int value.

my_num = 34567

result = int( str(my_num)[::-1] )

print(result)

Output

76543

Reverse a String in Python

We can use the slicing to reverse a String in Python. Like numbers,  we don't need to convert a String to anything. We can use the slicing of String easily and reverse it with one line of code.

input_str = "reverse this string"

result = input_str[::-1]

print(result)

Output

gnirts siht esrever

Create a Python Function to reverse number or string

def reverse_it(value):
  return value[::-1]

#reverse a string
print( reverse_it('triangle') ) # -> elgnairt

# revers a number
print( reverse_it(str(12345)) ) # -> 54321
Was this helpful?
0 Comments