
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if a string can be repeated to make another string in Python
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
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
- Related Articles
- Check if a string can be formed from another string using given constraints in Python
- Check if a string can be obtained by rotating another string 2 places in Python
- Check if a string can be converted to another string by replacing vowels and consonants in Python
- Check If a String Can Break Another String in C++
- JavaScript Program to Check if a string can be obtained by rotating another string d places
- JavaScript Program to Check if a string can be obtained by rotating another string by 2 places
- Program to check whether one string can be 1-to-1 mapped into another string in Python
- How to check if a string can be converted to float in Python?
- Write a program in C++ to check if a string can be obtained by rotating another string by two places
- Write a program in Java to check if a string can be obtained by rotating another string by 2 places
- Program to check we can replace characters to make a string to another string or not in C++
- Check if a string can be rearranged to form special palindrome in Python
- Check if a string is suffix of another in Python
- Check if string contains another string in Swift
- JavaScript Program to Check if a string can be formed from another string by at most X circular clockwise shifts

Advertisements