Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I tell if a string repeats itself in Python?
In Python, you can check if a string is composed of repeating substrings using several approaches. A string repeats itself when it's made up of one or more occurrences of a smaller pattern.
Using String Slicing and find()
The most elegant approach uses string concatenation and the find() method. By searching for the original string within a doubled version (excluding first and last characters), we can detect if it has a repeating pattern ?
def find_repeating_pattern(s):
i = (s + s).find(s, 1, -1)
return None if i == -1 else s[:i]
# Example with repeating pattern
text1 = '012012012012012'
print("The given string is:", text1)
pattern = find_repeating_pattern(text1)
print("Repeating pattern:", pattern)
The given string is: 012012012012012 Repeating pattern: 012
Example with Non-Repeating String
def find_repeating_pattern(s):
i = (s + s).find(s, 1, -1)
return None if i == -1 else s[:i]
# Example with non-repeating string
text2 = 'abcdefgh'
print("The given string is:", text2)
pattern = find_repeating_pattern(text2)
print("Repeating pattern:", pattern)
The given string is: abcdefgh Repeating pattern: None
Using Brute Force Approach
This method systematically checks all possible substring lengths to find a repeating pattern. It tests if the string can be formed by repeating a smaller substring ?
def find_pattern_brute_force(text):
for i in range(1, len(text) // 2 + 1):
pattern = text[:i]
if len(text) % len(pattern) == 0:
repetitions = len(text) // len(pattern)
if pattern * repetitions == text:
return pattern
return None
text = '012012012012012'
print("The given string is:", text)
result = find_pattern_brute_force(text)
print("Repeating pattern:", result)
The given string is: 012012012012012 Repeating pattern: 012
Boolean Check for Repetition
Sometimes you just need to know if a string repeats, not what the pattern is ?
def is_repeating_string(s):
return (s + s).find(s, 1, -1) != -1
# Test with different strings
test_strings = ['abcabc', 'aaaa', 'abcd', '121212']
for string in test_strings:
result = is_repeating_string(string)
print(f"'{string}' repeats: {result}")
'abcabc' repeats: True 'aaaa' repeats: True 'abcd' repeats: False '121212' repeats: True
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| String + find() | O(n) | Fast detection |
| Brute Force | O(n²) | Understanding the logic |
| Boolean Check | O(n) | Simple yes/no answer |
Conclusion
The string concatenation with find() method is the most efficient approach for detecting repeating patterns in strings. Use the brute force method when you need to understand the underlying logic or implement custom validation rules.
