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 for removing i-th character from a string
Next article icon

Python program to repeat M characters of a string N times

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

In this article, the task is to write a Python program to repeat M characters of string N times.

Method 1:

  1. Define a function that will take a word, m, and n values as arguments.
  2. If M is greater than the length of the word. Set m value equal to the length of the word
  3. Now store the characters needed to be repeated into a string named repeat_string using slicing.
  4. Initialize an empty string named as a result
  5. Concatenate the repeat_string to result for n times.
  6. Now print the string.

Below is the implementation:

Python3




def repeat(word, m, n):
 
    # if number of characters greater than length of word.
    # set number of characters = length of word
    if(m > len(word)):
        m = len(word)
 
    repeat_word = word[:m]
    result = ""
 
    for i in range(n):
        result = result+repeat_word
    print(result)
 
 
# driver code
repeat("geeks", 2, 3)
 
 

Output:

gegege

Time Complexity : O(n)
Auxiliary Space : O(n)

Method 2:

  1. Define a function that will take a word, m, n values as arguments.
  2. if M is greater than length of word. set m value equal to the length of word.
  3. Now store the characters needed to be repeated into a string named repeat_string using slicing.
  4. Multiply the repeat_string with n.
  5. Now print the string.

Python3




def repeat(word, m, n):
   
    # if number of characters greater than length of word.
    # set number of characters = length of word
    if(m > len(word)):
        m = len(word)
         
    repeat_word = word[:m]
    print(repeat_word*n)
 
# driver code
repeat("geeks", 2, 3)
 
 

Output:

gegege

The time and space complexity for both methods are the same:

Time Complexity : O(n)
Auxiliary Space : O(n)

Method 3: Using itertools

Here’s another method that can be used to repeat M characters of a string N times using the itertools module in Python:

Python3




import itertools
 
def repeat(word, m, n):
    if m > len(word):
        m = len(word)
         
    repeat_word = word[:m]
    result = "".join(itertools.islice(itertools.repeat(repeat_word), n))
    print(result)
 
# driver code
repeat("geeks", 2, 3)
 
 
Output
gegege

Time Complexity : O(n)
Auxiliary Space : O(n)

Method 4: Using operator.mul()+slicing

Approach

  1. Define a function that will take a word, m, n values as arguments.
  2. if M is greater than length of word. set m value equal to length of word.
  3. Now store the characters needed to be repeated into a string named repeat_string using slicing.
  4. Multiply the repeat_string with n.(using operator.mul())
  5. Now print the string.

Python3




def repeat(word, m, n):
 
    # if number of characters greater than length of word.
    # set number of characters = length of word
    if(m > len(word)):
        m = len(word)
         
    repeat_word = word[:m]
    import operator
    print(operator.mul(repeat_word,n))
 
# driver code
repeat("geeks", 2, 3)
 
 
Output
gegege

The time and space complexity for both methods is the same:

Time Complexity : O(n)
Auxiliary Space : O(n)



Next Article
Python program for removing i-th character from a string

P

pulamolusaimohan
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • 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 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
  • Python3 Program for Swap characters in a String
    Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
    5 min read
  • Python Program To Find Length Of The Longest Substring Without Repeating Characters
    Given a string str, find the length of the longest substring without repeating characters.  For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.For “BBBB” the longest substring is “B”, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
    6 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 print k characters then skip k characters in a string
    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 #
    5 min read
  • Python Program to get number of consecutive repeated substring
    Given a substring K, the task is to write a Python Program to find the repetition of K string in each consecutive occurrence of K. Example Input : test_str = 'geeksgeeks are geeksgeeksgeeks for all geeks', K = "geeks" Output : [2, 3, 1] Explanation : First consecution of 'geeks' is 2. Input : test_s
    4 min read
  • Python | Ways to remove n characters from start of given string
    Given a string and a number 'n', the task is to remove a string of length 'n' from the start of the string. Let's a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # how to remove 'n' characters from starting # of a string # Initialising st
    3 min read
  • Iterate over characters of a string in Python
    In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach. Using for loopThe simplest way to iterate over the characters in
    2 min read
  • Remove Multiple Characters from a String in Python
    Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Let’s explore the different ways to achieve this in det
    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