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 - Kth Valid String
Next article icon

Python | Repeat String till K

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

Sometimes, while working with strings, we might encounter a use case in which we need to repeat our string to the size of K, even though the last string might not be complete, but has to stop as the size of string becomes K. The problem of repeating string K times, is comparatively simpler than this problem. Let's discuss way outs we can perform to solve this problem. 

Method #1 : Using list slicing and // operator

This task can be performed using the above tools. In this we just multiply the string till it becomes greater than or equal to K, and then just omit the slice of extra string using the list slicing method. 

Python3
# Python3 code to demonstrate # Repeat string till K # using list slicing and // operator  # initializing string test_string = "GeeksforGeeks"  # initializing K K = 30  # printing original string print("The original string : " + str(test_string))  # using list slicing and // operator # Repeat string till K res = (test_string * (K//len(test_string) + 1))[:K]  # print result print("String after performing repetition : " + res) 

Output : 
The original string : GeeksforGeeks String after performing repetition : GeeksforGeeksGeeksforGeeksGeek

 

Time complexity: O(n)
Auxiliary space: O(n)

Method #2 : Using divmod() + list slicing

The division applied in the above method can be substituted in this method with the divmod function, which improves code readability with the cost of 40% of performance degradation.

Python3
# Python3 code to demonstrate # Repeat string till K # using divmod() + list slicing  # initializing string test_string = "GeeksforGeeks"  # initializing K K = 30  # printing original string print("The original string : " + str(test_string))  # using divmod() + list slicing # Repeat string till K div, mod = divmod(K, len(test_string)) res = test_string * div + test_string[:mod]  # print result print("String after performing repetition : " + res) 

Output : 
The original string : GeeksforGeeks String after performing repetition : GeeksforGeeksGeeksforGeeksGeek

 

Time complexity: O(1) since the operations are not dependent on the size of the input.
Auxiliary space: O(len(test_string)) since we create a string of length len(test_string) to store the repeated string.

Method #3: Using while loop and slicing

Python3
# Python3 code to demonstrate # Repeat string till K  # initializing string test_string = "GeeksforGeeks"  # initializing K K = 30  # printing original string print("The original string : " + str(test_string)) res = "" while(len(res) <= K):     res += test_string # print result print("String after performing repetition : " + res[:K]) 

Output
The original string : GeeksforGeeks String after performing repetition : GeeksforGeeksGeeksforGeeksGeek

Time complexity: O(K), where K is the maximum length of the repeated string.

Auxiliary space: O(K), as we are creating a new string 'res' to store the repeated string, and its maximum length can be K.

Method 4 : use the math module to determine the number of times the string needs to be repeated to reach the desired length, and then concatenate the string accordingly. 

step-by-step approach:

Import the math module.
Initialize the original string and the desired length K.
Calculate the length of the original string using the len() function.
Calculate the number of times the original string needs to be repeated to reach the desired length using the math.ceil() function, which rounds up the result to the nearest integer.
Concatenate the original string the required number of times using string multiplication.
Trim the concatenated string to the desired length K using list slicing.
Print the final string.

Python3
import math  # initializing string test_string = "GeeksforGeeks"  # initializing K K = 30  # calculating length of original string length = len(test_string)  # calculating number of repetitions required repetitions = math.ceil(K/length)  # concatenating the string the required number of times res = test_string * repetitions  # trimming the concatenated string to the desired length res = res[:K]  # print result print("String after performing repetition : " + res) 

Output
String after performing repetition : GeeksforGeeksGeeksforGeeksGeek

Time complexity: The time complexity of this approach is O(K), where K is the maximum length of the repeated string.
Auxiliary space: The auxiliary space used by this approach is also O(K), 


Next Article
Python - Kth Valid String
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • How to Repeat a String in Python?
    Repeating a string is a simple task in Python. We can create multiple copies of a string by using built-in features. This is useful when we need to repeat a word, phrase, or any other string a specific number of times. Using Multiplication Operator (*):Using Multiplication operator (*) is the simple
    2 min read
  • Python - Check if string repeats itself
    Checking if a string repeats itself means determining whether the string consists of multiple repetitions of a smaller substring. Using slicing and multiplicationWe can check if the string is a repetition of a substring by slicing and reconstructing the string using multiplication. [GFGTABS] Python
    3 min read
  • Reverse Sort a String - Python
    The goal is to take a given string and arrange its characters in descending order based on their Unicode values. For example, in the string "geeksforgeeks", the characters will be sorted from highest to lowest, resulting in a new string like "ssrokkggfeeeee". Let's understand different methods to pe
    2 min read
  • Python | Split by repeating substring
    Sometimes, while working with Python strings, we can have a problem in which we need to perform splitting. This can be of a custom nature. In this, we can have a split in which we need to split by all the repetitions. This can have applications in many domains. Let us discuss certain ways in which t
    5 min read
  • Python - Kth Valid String
    Sometimes while dealing with data science, we need to handle a large amount of data and hence we may require shorthands to perform certain tasks. We handle the Null values at preprocessing stage and hence sometimes require to check for the Kth valid element. Let’s discuss certain ways in which we ca
    3 min read
  • Python - Reversed Split Strings
    In Python, there are times where we need to split a given string into individual words and reverse the order of these words while preserving the order of characters within each word. For example, given the input string "learn python with gfg", the desired output would be "gfg with python learn". Let
    3 min read
  • How to copy a string in Python
    Creating a copy of a string is useful when we need a duplicate of a string to work with while keeping the original string intact, strings in Python are immutable which means they can't be altered after creation, so creating a copy sometimes becomes a necessity for specific use cases. Using SlicingSl
    2 min read
  • Python - Phrase removal in String
    Sometimes, while working with Python strings, we can have a problem in which we need to extract certain words in a string excluding the initial and rear K words. This can have application in many domains including all those include data. Lets discuss certain ways in which this task can be performed.
    2 min read
  • How to Count Repeated Words in a String in Python
    In this article, we will learn how to count repeated words in a string. Python provides several methods to Count Repeated Words , such as dictionaries, collections. Counter module, or even regular expressions. The simplest way to count repeated words is by splitting the string into individual words
    2 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
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