# How can I tell if a string repeats itself in Python?

In this article, we are going to find out how can we tell if a string repeats itself in Python.

The first approach is by using slicing and find(). We want to see if the string we have is made up entirely of repeats of a substring of the string. We can confirm this by looking for a rotation of the string in a pair of strings.

After adding a string and checking the root string in this string, except for the last and first character, we may search for the root string. This approach doesn’t work for strings with length less than 2.

## Example 1

In the example given below, we are taking a string as input and we are checking if it is repeating using slicing and find() method

def find_period(s):
i = (s+s).find(s, 1, -1)
return None if i == -1 else s[:i]

str1 = '012012012012012'
print("The given string is")
print(str1)

print("Checking if any substring that is repeating")
res = find_period(str1)
print(res)


## Output

The output of the above example is as shown below −

The given string is
012012012012012
Checking if any substring that is repeating
012


## Example 2

In the example given below, we are taking the same program as above but we are taking a different input and checking if it is repeating

def find_period(s):
i = (s+s).find(s, 1, -1)
return None if i == -1 else s[:i]

str1 = 'abcdefgh'
print("The given string is")
print(str1)

print("Checking if any substring that is repeating")
res = find_period(str1)
print(res)


## Output

The output of the above example is given below −

The given string is
abcdefgh
Checking if any substring that is repeating
None


## Using brute force approach

The second approach is brute force approach, we will keep on iterating over the string and checking for repetitive sequences. This work can be accomplished by selective slicing and brute force methods. This is a primitive approach of string discovery in which we try to identify the root string by repeatedly dividing the string.

### Example

In the example given below, we are taking a string as input and we are checking if any part of the string is repetitive using list comprehensions

str1 = '012012012012012'

print("The given string is")
print(str1)

print("Checking if any substring that is repeating")
res = None

for i in range(1, len(str1)//2 + 1):
if (not len(str1) % len(str1[0:i]) and str1[0:i] *(len(str1)//len(str1[0:i])) == str1):
res = str1[0:i]
print(res)


### Output

The output of the above example is given below −

The given string is
012012012012012
Checking if any substring that is repeating
012


Updated on: 07-Dec-2022

480 Views