Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python program to repeat M characters of a string N times
Next article icon

Python program to print k characters then skip k characters in a string

Last Updated : 24 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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))
 
 
Output
The 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))
 
 
Output
The 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.
 
 
Output
The 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))
 
 
Output
The 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

  1. Define a function named chunk_generator that takes two arguments: a string s and an integer k.
  2. 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.
  3. 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.
  4. In the main program, initialize a string test_str and an integer K.
  5. Call the chunk_generator function with the test_str and K arguments. This generates a generator object that yields chunks of K characters.
  6. Use the join method to concatenate the chunks into a single string, and assign the result to a variable named res.
  7. 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))
 
 
Output
Transformed 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.



Next Article
Python program to repeat M characters of a string N times
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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 read character by character from a file
    Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by charact
    2 min read
  • Python program to repeat M characters of a string N times
    In this article, the task is to write a Python program to repeat M characters of string N times. Method 1: Define a function that will take a word, m, and n values as arguments.If M is greater than the length of the word. Set m value equal to the length of the wordNow store the characters needed to
    3 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 calculate the number of words and characters in the string
    We are given a string we need to find the total number of words and total number of character in the given string. For Example we are given a string s = "Geeksforgeeks is best Computer Science Portal" we need to count the total words in the given string and the total characters in the given string.
    3 min read
  • Python program to Replace all Characters of a List Except the given character
    Given a List. The task is to replace all the characters of the list with N except the given character. Input : test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G' Output : ['G', '*', 'G', '*', '*', '*', '*', '*', '*'] Explanation : All characters except G replace
    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 mo
    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
    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
  • Python program to find the character position of Kth word from a list of strings
    Given a list of strings. The task is to find the index of the character position for the word, which lies at the Kth index in the list of strings. Examples: Input : test_list = ["geekforgeeks", "is", "best", "for", "geeks"], K = 21 Output : 0Explanation : 21st index occurs in "geeks" and point to "g
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences