# Check if a string can be repeated to make another string in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s and t, we have to find how many times the string s can be concatenated to generate t. If we cannot generate t using s, then return -1.

So, if the input is like s = "tom" t = "tomtomtom", then the output will be 3 as we can concatenate "tom" 3 times to get "tomtomtom".

To solve this, we will follow these steps −

• if size of t is not divisible by size of s, then
• return -1
• cnt := quotient of (size of t / size of s)
• s := concatenate s cnt number of times
• if s is same as t, then
• return cnt
• return -1

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(s, t):
if(len(t) % len(s) != 0):
return -1;
cnt = int(len(t) / len(s))
s = s * cnt
if(s == t):
return cnt
return -1
s = "tom"
t = "tomtomtom"
print(solve(s, t))

## Input

"tom", "tomtomtom"

## Output

3
Published on 29-Dec-2020 13:10:20