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:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- Define a function that will take a word, m, n values as arguments.
- If M is greater than the length of the word. Set m value equal to the length of the word
- Now store the characters needed to be repeated into a string named repeat_string using slicing.
- Initialize an empty string named as a result
- Concatenate the repeat_string to result for n times.
- 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 coderepeat("geeks", 2, 3) |
Output:
gegege
Method 2:
- Define a function which will take a word, m, n values as arguments.
- if M is greater than length of word. set m value equal to length of word
- Now store the characters needed to be repeated into a string named repeat_string using slicing.
- Multiply the repeat_string with n.
- 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 coderepeat("geeks", 2, 3) |
Output:
gegege


