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.
Highlighted programs for you
University of Maryland Global Campus
University of Maryland Global Campus
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 –
- Converting the string into a list of words.
- By chaining multiple string
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
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)
['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)
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
word2 in a string, first, replace
word1 with a temporary string, let’s say
temp, now replace
word1, and then, finally, replace the
temp string with
word2. The following chart illustrates this better.
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)
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))
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
word2 and vice-versa so it will not work if you want to swap only specific occurrences of two words.
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.
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.
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
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 –
- Swap Elements in a Python List with these Methods
- Convert Python String to a List
- Split String by Substring in Python
- Python – Remove Multiple Spaces From a String
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.