Python Program To Reverse a Number Using List Slicing

Python Program To Reverse a Number Using List Slicing

In this tutorial, you will learn to write a Python Program To Reverse a Number Using List Slicing.

To understand this program you should have an understanding of the following topics:

  1. For Loop
  2. Python Lists

Python Program To Reverse a Number Using List Slicing

num = int(input("Enter a number: "))
num_str = str(num)

reverse_str = num_str[::-1]
reverse_num = int(reverse_str)

print("The reversed number is:", reverse_num)

Output

Enter a number: 12789nThe reversed number is: 98721

We first prompt the user to input a number.

We then convert the number to a string using str(num) and store it in a variable called num_str.

We then use list slicing to reverse the string.

The syntax for list slicing is start:stop:step.

In this case, we set to start to -1, which means we start at the last character of num_str.

We set stop to None, which means we go up to the first character of num_str.

We set step to -1, which means we iterate backward over the string.

We then store the reversed string in a variable called reverse_str.

Finally, we convert the reversed string back to an integer using int(reverse_str) and store it in a variable called reverse_num.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading