Python | Custom Consecutive Character Pairing
Last Updated :
24 Apr, 2023
Sometimes, while working with Python Strings, we can have problem in which we need to perform the pairing of consecutive strings with deliminator. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using join() + list comprehension The combination of above functions can be used to perform this task. In this, we perform the task of joining the characters using join() and perform the compilation using list comprehension.
Python3
import string
test_str = 'geeksforgeeks'
print ("The original string is : " + test_str)
delim = '_'
res = [delim.join(test_str[idx : idx + 2 ]) for idx in range ( len (test_str) - 1 )]
print ("The List of joined Characters : " + str (res))
|
Output :
The original string is : geeksforgeeks
The List of joined Characters : ['g_e', 'e_e', 'e_k', 'k_s', 's_f', 'f_o', 'o_r', 'r_g', 'g_e', 'e_e', 'e_k', 'k_s']
Method #2 : Using windowed() + loop This is one of the method to solve this problem. In this task of forming pairs is done using windowed(). You need to install more_itertools module externally for its execution.
Python3
import more_itertools
test_str = 'geeksforgeeks'
print ("The original string is : " + test_str)
delim = '_'
res = []
for ele in more_itertools.windowed(test_str, 2 ):
res.append(ele[ 0 ] + delim + ele[ 1 ])
print ("The List of joined Characters : " + str (res))
|
Output :
The original string is : geeksforgeeks
The List of joined Characters : ['g_e', 'e_e', 'e_k', 'k_s', 's_f', 'f_o', 'o_r', 'r_g', 'g_e', 'e_e', 'e_k', 'k_s']
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Another approach to perform Custom Consecutive Character Pairing
Using zip() function
Zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
Python3
def custom_pairing(test_str, delim):
result = [delim.join(pair) for pair in zip (test_str, test_str[ 1 :])]
return result
test_str = 'geeksforgeeks'
delim = '_'
print (custom_pairing(test_str, delim))
|
Output
['g_e', 'e_e', 'e_k', 'k_s', 's_f', 'f_o', 'o_r', 'r_g', 'g_e', 'e_e', 'e_k', 'k_s']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #8: Using a generator function and str.join()
step-by-step breakdown of the program:
- Define the input string test_str as ‘geeksforgeeks’.
- Print the original string by concatenating the string ‘The original string is : ‘ and test_str.
- Define the delimiter as ‘_’.
- Define a generator function consecutive_pairs that takes in a string string and yields consecutive character pairs in the form of tuples. This is done by iterating over the range of the length of the string minus one, and yielding a tuple of the current character and the next character in the string using slicing.
Call the consecutive_pairs function with test_str as the argument and pass the resulting generator to a list comprehension that creates a list of strings where each element is a pair of consecutive characters joined by the delimiter. This is done by calling ”.join(pair) on each pair of characters in the generator and concatenating the delimiter between them.
- Assign the resulting list to the variable res.
- Print the list of joined characters by concatenating the string ‘The List of joined Characters : ‘ and str(res).
Python3
test_str = 'geeksforgeeks'
print ( "The original string is : " + test_str)
delim = '_'
def consecutive_pairs(string):
for i in range ( len (string) - 1 ):
yield string[i:i + 2 ]
res = [delim.join(pair) for pair in consecutive_pairs(test_str)]
print ( "The List of joined Characters : " + str (res))
|
Output
The original string is : geeksforgeeks
The List of joined Characters : ['g_e', 'e_e', 'e_k', 'k_s', 's_f', 'f_o', 'o_r', 'r_g', 'g_e', 'e_e', 'e_k', 'k_s']
Time complexity: O(n)
Auxiliary space: O(n), where n is the length of the input string.
Similar Reads
Python - K length consecutive characters
Given a String, extract all the K-length consecutive characters. Input : test_str = 'geekforgeeeksss is bbbest forrr geeks', K = 3 Output : ['eee', 'sss', 'bbb', 'rrr'] Explanation : K length consecutive strings extracted. Input : test_str = 'geekforgeeeksss is bbbest forrrr geeks', K = 4 Output : [
4 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
Consecutive characters frequency - Python
This problem involves identifying characters that appear consecutively and counting how many times they appear together. Here, we will explore different methods to calculate the frequency of consecutive characters in a string. Using regular expressionsWe can use the re module to efficiently count co
3 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 | 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 - Consecutive Repetition of Characters
Sometimes, while working with character lists we can have a problem in which we need to perform consecutive repetition of characters. This can have applications in many domains. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is one of the
5 min read
Python - All Position Character Combination
To generate all position character combinations from a string we need to create combinations of characters from the string where each combination is formed by selecting characters at different positions. We can use functions like combinations() from itertools or custom loop approach. For Example let
2 min read
Python - Consecutive Triple element pairing
Sometimes, while working with lists, we need to triple pair up the like elements in list and then store them as lists of list. This particular task has itâs utility in many domains, be it web development or day-day programming. Letâs discuss certain ways in which this can be achieved. Method #1 : Us
4 min read
Python - Character coordinates in Matrix
Sometimes, while working with Python data, we can have a problem in which we need to extract all the coordinates in Matrix, which are characters. This kind of problem can have potential application in domains such as web development and day-day programming. Let's discuss certain ways in which this t
5 min read
Python | Consecutive elements pairing in list
This process involves creating pairs of elements that appear next to each other, which can be invaluable for various applications such as data analysis, pattern recognition and algorithm development. We can achieve this using different methods in Python, such as using simple loops, list slicing, zip
4 min read