How To Swap Digits Of A Number In Python

Swapping digits of a number is a relatively simple task, but it can provide a solid foundation for learning how to manipulate numbers and their positions in Python.

This tutorial will specifically focus on how to create a Python function that can be used to swap the digits of a number.

By following the steps outlined below, you’ll be able to create this function and gain a better understanding of digit manipulation in Python.

Step 1: Accepting User Input

First, we need to accept an integer input from the user. We’ll later use this input to test the swapping function. You can use the input() function to grab input from the user and convert it to an integer with the int() function.

Here’s an example of how to accept an integer from the user:

Step 2: Separate the Digits

Next, it’s necessary to separate the digits of the user’s inputted number. One method to achieve this is by converting the number into a list of individual digits. To do this, we can use a list comprehension on the input string.

Here’s how you can separate the digits of the user’s input:

The str() function converts the number to a string, which is then iterated through by the list comprehension, and the int() function converts each digit back to an integer.

Step 3: Create the Swapping Function

Now that we have all the digits in a list, we can create a function to swap the desired digits. For this example, we’ll swap the first and second digits of the input number. To achieve this, create a function called swap_digits:

The swap_digits function accepts a list of digits, and the positions to be swapped – pos1 and pos2. It then swaps the digits using tuple unpacking.

Step 4: Perform the Swap and Display the Result

Now apply the function to the list of digits and join the resulting list to form the output number.

The map() function is used to convert the swapped digits back to strings, and the join() function combines them into a single string. Finally, the int() function is used to convert the final string back into an integer.

Display the output to the user:

Full Code

Output

Enter a number: 19
The number after swapping the first two digits:  91

Conclusion

By following this tutorial, you have successfully created a Python function that can swap any two digits of a number. Not only is this a useful skill for solving various programming problems, but it also helps improve your understanding of list comprehensions, tuple unpacking, and digit manipulation in Python.

Keep practicing with different positions and input values to enhance your skills, and continue exploring other ways to manipulate numbers in Python.