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
test_str = "gfgisbesty"
print ("The original string is : " + test_str)
res = ''.join([char[ 1 ] + char[ 0 ] for char in zip (test_str[:: 2 ], test_str[ 1 :: 2 ])])
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
import re
test_str = "gfgisbesty"
print ("The original string is : " + test_str)
res = re.sub(r '(.)(.)' , r '\2\1' , test_str)
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
test_str = "gfgisbesty"
print ( "The original string is : " + test_str)
res = ''
for i in range ( 0 , len (test_str) - 1 , 2 ):
res + = test_str[i + 1 ] + test_str[i]
print ( "String after Consecutive Swapping : " + str (res))
|
Output
The 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
my_string = "gfgisbesty"
my_string = my_string[ 1 :: 2 ] + my_string[ 0 :: 2 ]
print (my_string)
|
Time complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...