Python | Consecutive element swapping in String
Last Updated :
09 Apr, 2023
Sometimes, while working with strings, we can have a problem in which we may require to perform swapping of consecutive elements in string. Let's discuss certain ways in which this task can be performed.
Method #1 : Using join() + zip() + generator expression The combination of above functions can be used to solve this problem. In this, we perform the task of joining consecutive characters using zip() and generator expression is used to provide the swap logic.
Python3
# Python3 code to demonstrate working of
# Consecutive element swapping in String
# using join() + zip() + generator expression
# initializing string
test_str = "gfgisbesty"
# printing original string
print("The original string is : " + test_str)
# Consecutive element swapping in String
# using join() + zip() + generator expression
res = ''.join([char[1] + char[0] for char in zip(test_str[::2], test_str[1::2])])
# printing result
print("String after Consecutive Swapping : " + str(res))
Output : The original string is : gfgisbesty
String after Consecutive Swapping : fgigbsseyt
Time Complexity: O(n*nlogn) where n is the number of elements in the string list. The join() + zip() + generator expression is used to perform the task and it takes O(n*nlogn) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the string list.
Method #2 : Using regex expression This task can also be performed using regular expression using correctly framed regex.
Python3
# Python3 code to demonstrate working of
# Consecutive element swapping in String
# using regular expression
import re
# initializing string
test_str = "gfgisbesty"
# printing original string
print("The original string is : " + test_str)
# Consecutive element swapping in String
# using regular expression
res = re.sub(r'(.)(.)', r'\2\1', test_str)
# printing result
print("String after Consecutive Swapping : " + str(res))
Output : The original string is : gfgisbesty
String after Consecutive Swapping : fgigbsseyt
Time Complexity: O(n) where n is the number of elements in the string list. The regex is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test_list.
Method #3 : Using for loop
This task can also be performed using for loop, by performing the swapping logic in loop.
Python3
# Python3 code to demonstrate working of
# Consecutive element swapping in String
# using for loop
# initializing string
test_str = "gfgisbesty"
# printing original string
print("The original string is : " + test_str)
# Consecutive element swapping in String
# using for loop
res = ''
for i in range(0, len(test_str) - 1, 2):
res += test_str[i + 1] + test_str[i]
# printing result
print("String after Consecutive Swapping : " + str(res))
#this code is contributed by edula vinay kumar reddy
OutputThe original string is : gfgisbesty
String after Consecutive Swapping : fgigbsseyt
Time complexity: O(n)
Auxiliary Space: O(1)
Method #4:Using slicing and string concatenation
Python3
# Initialize the string
my_string = "gfgisbesty"
# Swap consecutive elements
my_string = my_string[1::2] + my_string[0::2]
# Print the updated string
print(my_string)
#This Code is contributed by Vinay Pinjala.
Time complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Python - Consecutive element deletion strings Sometimes, while working with Python, we can have a problem in which we have a string and wish to extract all possible combination of words after deletion of consecutive elements one at a time. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
6 min read
Swap elements in String list - Python Swapping elements in a string list means we need to exchange one element with another throughout the entire string list in Python. This can be done using various methods, such as using replace(), string functions, regular expressions (Regex), etc. For example, consider the original list: ['Gfg', 'is
3 min read
Python - Selective consecutive Suffix Join Given a list of elements, the task is to write a Python program to perform a join of consecutive strings according to the suffix of each string. Input : test_list = ["Geeks-", "for-", "Geeks", "is", "best-", "for", "geeks", suff = '-' Output : ['Geeks-for-Geeks', 'is', 'best-for', 'geeks'] Explanati
2 min read
Python - Get Nth column elements in Tuple Strings Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
8 min read
Python - Equidistant consecutive characters Strings Given a Strings List, extract all the strings, whose consecutive characters are at the common difference in ASCII order. Input : test_list = ["abcd", "egil", "mpsv", "abd"] Output : ['abcd', 'mpsv'] Explanation : In mpsv, consecutive characters are at distance 3. Input : test_list = ["abcd", "egil",
9 min read
Python - Custom Consecutive character repetition in String Given a String, repeat characters consecutively by number mapped in dictionary. Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k" : 5, "s" : 3} Output : GGGeekkkkksss444GGGeekkkkksss Explanation : Each letter repeated as per value in dictionary.Input : test_str = 'Geeks4G
4 min read
Python | Pair the consecutive character strings in a list Sometimes while programming, we can face a problem in which we need to perform consecutive element concatenation. This problem can occur at times of school programming or competitive programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + z
5 min read
Python - Alternate Strings Concatenation The problem of getting the concatenation of a list is quite generic and we might someday face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing the concatenation of alternate elements. Letâs discuss certain ways in which this can be performed. Met
3 min read
Python3 Program for Swap characters in a String Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
5 min read
Convert String to Tuple - Python When we want to break down a string into its individual characters and store each character as an element in a tuple, we can use the tuple() function directly on the string. Strings in Python are iterable, which means that when we pass a string to the tuple() function, it iterates over each characte
2 min read