How to Swap Words in a String in Python

In this tutorial, you will learn how to swap words in a string using Python. The task is to interchange two words in a string. This can be done in Python with just a few lines of code. This skill can be very useful, for example, when you are handling and manipulating text data in data analysis or doing any kind of text processing.

Step 1: Define your string

First of all, you have to define the string where you want to swap the words. You can do this by assigning your text to a variable. For example:

Step 2: Use the replace function to swap words

Python string has a built-in method called replace(). This method replaces a specified phrase with another specified phrase. We can use this method to swap words in our string:

In the above code, we are using a temporary word “temp” to make the swap possible. First, we replace the word ‘Python’ with ‘temp’, then ‘coding’ with ‘Python’, and finally ‘temp’ with ‘coding’.

Step 3: Print the result

Finally, let’s print the resulting text with the swapped words:

The Output

In this example, the words ‘Python’ and ‘coding’ have been swapped in the string. So, the output will be:

I love coding Python

This is a simple yet powerful technique for manipulating strings in Python.

Here is the complete code:

Conclusion

In this tutorial, you learned how to swap words in a string using Python. This is done by using a temporary word with the replace() string method in Python. This method can be helpful in a number of different scenarios when it comes to text manipulation. Keep exploring and happy coding!