swap two words in a python string

Swap Two Words in a String with these Methods in Python

In this tutorial, we will look at how to swap two words in a string in Python with the help of some examples.

If you prefer a video tutorial over text, check out the following video detailing the steps in this tutorial.

How is swapping words different from replacing words in a String?

Note that swapping words and replacing words are two different things.

You can replace a string with another string using the string replace() function. When you’re replacing a string with a new string, you’re simply substituting a new string (that may or may not be present in the original string) in place of the original string. Swapping words, on the other hand, means you’re switching the position of two words that are already present in the string.

If you want to swap two characters in a string, check out our detailed guide on swapping characters in a Python string.

How to swap two words in a string?

Let’s look at an example to see what we mean by swapping words in a string –

In the string, “It was raining cats and dogs”, you want to swap the words “cats” and “dogs” such that the resulting string becomes “It was raining dogs and cats”.

There’s no direct method to swap two words (substrings) inside a string in Python but we can use other methods like the following to achieve the desired outcome –

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

  1. Converting the string into a list of words.
  2. By chaining multiple string replace() functions together.

Let’s now look at both the above methods in detail.

Method 1 – Converting the string to a list of words

In this method, we create a list of words from the string using the string split() function and then use the indices of the relevant words to swap them in the list and finally, get the resulting string back using the string join() method.

image showing words in a list getting swapped

Let’s look at an example.

# create a string
s = "It was raining cats and dogs"
# create a list of words from the string
ls = s.split(" ")
# display the resulting list
print(ls)

Output:

['It', 'was', 'raining', 'cats', 'and', 'dogs']

You can see that we now have the words from the string in a list. Now, swapping two words is as simple as swapping two elements in a list. To swap the words “cats” and “dogs”, we use their respective index.

# indices of elements to swap
i = 3
j = 5
# swap words at index i and j
ls[i], ls[j] = ls[j], ls[i]
# join the list elements together into a string
result = " ".join(ls)
print(result)

Output:

It was raining dogs and cats

You can see that we get the resulting string with the required words swapped. Note that strings are immutable in Python and hence cannot be modified after they are created (you can, however, reassign a variable to a new string value).

Note that if your string has punctuation, you may want to remove them before using this method. Or, try to split the string such that the punctuations are not with the words you want to swap (for example, using regular expressions).

Method 2 – Chaining multiple string replace() functions together

Here, we chain multiple string replace() functions together. The idea is similar to swapping two variables using another temporary variable. Let’s say you want to swap word1 and word2 in a string, first, replace word1 with a temporary string, let’s say temp, now replace word2 with word1, and then, finally, replace the temp string with word2. The following chart illustrates this better.

image showing how the chain of changes from "cats and dogs" to "dogs and cats" using a "TEMP" replacement

Let’s take the same example as above –

# create a string
s = "It was raning cats and dogs"
# the words to swap
word1 = "cats"
word2 = "dogs"
# swap the words
result = s.replace(word1, "TEMP").replace(word2, word1).replace("TEMP", word2)
print(result)

Output:

It was raning dogs and cats

Here, we are using the string replace() function three times. Let’s print out the original string and the outcome of each of the three replace functions to see how the swapping is taking place.

print(s)
print(s.replace(word1, "TEMP"))
print(s.replace(word1, "TEMP").replace(word2, word1))
print(s.replace(word1, "TEMP").replace(word2, word1).replace("TEMP", word2))

Output:

It was raning cats and dogs
It was raning TEMP and dogs
It was raning TEMP and cats
It was raning dogs and cats

The above output shows how we go from “It was raining cats and dogs” to “It was raining dogs and cats” using this method.

Note that the above method will replace every occurrence of word1 with word2 and vice-versa so it will not work if you want to swap only specific occurrences of two words.

FAQs

How to swap two words in a string?

To swap two words, you can create a list of words from the string, swap them based on their index and join them back together to a string. Alternatively, you can chain multiple string replace() functions together to swap two words.

What if the string has punctuation when using the list method?

In that case, try to separate the words from the punctuations (for example, using regular expressions) and then create a list from only the words.

How is the list method different from the chaining of the replace() function method?

If there are multiple occurrences of the words to be swapped in the string, we can choose which two specific words to swap in the list method (because it uses the index to swap) but the replace() function method will swap every occurrence of word1 with word2 and vice-versa, that is, it will not work if we want to swap only specific occurrences of the words.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top