Home » Python » Python programs

# Python program to repeat M characters of a string N times

Here, we are going to learn **how to repeat a given number of characters (M) of a string N (given number) times using python program?**

Submitted by Suryaveer Singh, on June 08, 2019

Given a string and we have to repeat it's **M** characters **N** times using python program.

**Question:**

Here we are provided with a string and a non-negative integer **N**, here we would consider that the front of the string is first **M** characters, or whatever is there in the string if the string length is less than **M**. Now our task is to **return N copies of the front**. Also, consider these cases,

**Example:**

mult_times('Chocolate', 3, 2) = 'ChoCho' mult_times('Chocolate', 4, 3) = 'ChocChocChoc' mult_times ('jio', 2, 3) = 'jijiji'

**Solution:**

Here we would first simply write code for string value equal to **M** or less. As we are unknown for the value of **N** we would store our string value in a variable and run a for loop for **N** times and each time we would store our value in that variable.

**Let's understand this by Code, which would be easier to understand,**

**Code:**

def mult_times(str, m, n): front_len = m if front_len > len(str): front_len = len(str) front = str[:front_len] result = '' for i in range(n): result = result + front return result print (mult_times('IncludeHelp', 7, 5)) print (mult_times('prem', 4, 3)) print (mult_times('Hello', 3, 7))

**Output**

IncludeIncludeIncludeIncludeInclude prempremprem HelHelHelHelHelHelHel

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.