Python program to print k characters then skip k characters in a string
Last Updated :
24 Apr, 2023
Given a String, extract K characters alternatively.
Input : test_str = 'geeksgeeksisbestforgeeks', K = 4
Output : geekksisforg
Explanation : Every 4th alternate range is sliced.
Input : test_str = 'geeksgeeksisbest', K = 4
Output : geekksis
Explanation : Every 4th alternate range is sliced.
Method #1 : Using loop + slicing
In this, we perform task of getting K characters using slicing, and loop is used to perform task of concatenation.
Python3
# Python3 code to demonstrate working of
# Alternate K Length characters
# Using loop + slicing
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
res = ''
# skipping k * 2 for altering effect
for idx in range(0, len(test_str), K * 2):
# concatenating K chars
res += test_str[idx : idx + K]
# printing result
print("Transformed String : " + str(res))
OutputThe original string is : geeksgeeksisbestforgeeks
Transformed String : geekksisforg
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using list comprehension + join()
This is similar to the above way, only difference being its one liner approach, and join() is used to perform task of convert back to string.
Python3
# Python3 code to demonstrate working of
# Alternate K Length characters
# Using list comprehension + join()
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# slicing K using slicing, join for converting back to string
res = ''.join([test_str[idx : idx + K] for idx in range(0, len(test_str), K * 2)])
# printing result
print("Transformed String : " + str(res))
OutputThe original string is : geeksgeeksisbestforgeeks
Transformed String : geekksisforg
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using map and lambda function.
Python3
# Python3 code to demonstrate working of
# Alternate K Length characters
# Using map and lambda function:
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
result = ''.join(map(lambda x: test_str[x:x+K], range(0, len(test_str), 2 * K)))
# printing result
print("Transformed String : " + str(result))
#this code contributed by tvsk.
OutputThe original string is : geeksgeeksisbestforgeeks
Transformed String : geekksisforg
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Here's an implementation using the reduce function from the functools module:
The reduce function applies the lambda function to the elements of the list and accumulates the results. In this case, the lambda function takes two arguments x and y, which are the previous and current elements in the list respectively, and concatenates them. The reduce function starts with the first two elements of the list and the result is the final concatenated string.
Python3
from functools import reduce
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# using reduce to concatenate the K characters
result = reduce(lambda x, y: x + y, [test_str[i:i+K] for i in range(0, len(test_str), 2 * K)])
# printing result
print("Transformed String : " + str(result))
OutputThe original string is : geeksgeeksisbestforgeeks
Transformed String : geekksisforg
The time and auxiliary space for this implementation will also be O(n).
Method 5 : using a generator function
step-by-step approach
- Define a function named chunk_generator that takes two arguments: a string s and an integer k.
- The function uses a for loop with a range of 0 to the length of the input string, with a step of k*2. This skips 2*k characters each time to alternate between the chunks.
- The loop yields a slice of the string, starting from index i and going up to index i+k. This slice contains a chunk of k characters from the input string.
- In the main program, initialize a string test_str and an integer K.
- Call the chunk_generator function with the test_str and K arguments. This generates a generator object that yields chunks of K characters.
- Use the join method to concatenate the chunks into a single string, and assign the result to a variable named res.
- Print the resulting string, with the message "Transformed String : " concatenated to the beginning of the string.
Python3
# defining chunk generator function
def chunk_generator(s, k):
for i in range(0, len(s), k*2):
yield s[i:i+k]
# initializing string and K
test_str = 'geeksgeeksisbestforgeeks'
K = 4
# generating chunks and joining them together
res = ''.join(chunk_generator(test_str, K))
# printing result
print("Transformed String : " + str(res))
OutputTransformed String : geekksisforg
Time complexity: The program has a time complexity of O(n/k), where n is the length of the input string and k is the length of each chunk.
Auxiliary space complexity: The program has an auxiliary space complexity of O(k), which is the size of each chunk.
Similar Reads
Python program to extract characters in given range from a string list Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best",
4 min read
Python program to remove the nth index character from a non-empty string Given a String, the task is to write a Python program to remove the nth index character from a non-empty string Examples: Input: str = "Stable" Output: Modified string after removing 4 th character Stabe Input: str = "Arrow" Output: Modified string after removing 4 th character Arro The first approa
4 min read
Python program to remove last N characters from a string In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions.Using String SlicingString slicing is one of the simplest and mos
2 min read
Python program for removing i-th character from a string In this article, we will explore different methods for removing the i-th character from a string in Python. The simplest method involves using string slicing.Using String SlicingString slicing allows us to create a substring by specifying the start and end index. Here, we use two slices to exclude t
2 min read
Python program to Extract string till first Non-Alphanumeric character Given a string, extract all the alphanumerics before 1st occurrence of non-alphanumeric. Input : test_str = 'geek$s4g!!!eeks' Output : geek Explanation : Stopped at $ occurrence. Input : test_str = 'ge)eks4g!!!eeks' Output : ge Explanation : Stopped at ) occurrence. Method #1 : Using regex + search(
4 min read
Count the number of characters in a String - Python The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this.Using len()len() is
2 min read
Python - Create a string made of the first and last two characters from a given string To solve the problem, we need to create a new string that combines the first two and the last two characters of a given string. If the input string is too short (less than 2 characters), we should return an empty string. This task is simple and can be achieved using a variety of methods.Using slicin
2 min read
Python - Convert String to matrix having K characters per row Given a String, convert it to Matrix, having K characters in each row. Input : test_str = 'GeeksforGeeks is best', K = 7 Output : [['G', 'e', 'e', 'k', 's', 'f', 'o'], ['r', 'G', 'e', 'e', 'k', 's', ' '], ['i', 's', ' ', 'b', 'e', 's', 't']] Explanation : Each character is assigned to 7 element row
9 min read
Python | Split string in groups of n consecutive characters Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character. Examples: Input : str = "Geeksforgeeks", n = 3 Output : ['Gee', 'ksf', 'org', 'eek', 's'] Input : str = "1234567891234567", n = 4 Output : [1234, 5678, 9123, 4567] Method
2 min read