Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check if String is Empty or Not - Python
Next article icon

Python – Check if string repeats itself

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Checking if a string repeats itself means determining whether the string consists of multiple repetitions of a smaller substring.

Using slicing and multiplication

We can check if the string is a repetition of a substring by slicing and reconstructing the string using multiplication.

Python
s = "ababab"  # Check if string repeats by slicing and multiplying res = s in (s + s)[1:-1] print(res)   

Output
True 

Explanation:

  • We concatenate the string with itself to allow rotation-based checks.
  • We remove the first and last characters of the concatenated string.
  • If the original string exists in this modified string, it means it is made up of repeated substrings.

Let’s explore some more methods and see how we can check if string repeats itself in python.

Table of Content

  • Using regular expressions
  • Using for loop
  • Using concatenation
  • Using string slicing and comparison

Using regular expressions

We can use a regular expression to check for a repeating pattern.

Python
import re s = "ababab"  # Check for repeating pattern using regex res = bool(re.fullmatch(r"(.+)\1+", s)) print(res)   

Output
True 

Explanation:

  • The regular expression (.+)\1+ checks for one or more occurrences of a substring followed by itself.
  • If the string matches this pattern, it repeats itself.

Using for loop

We can manually iterate through the string using a for loop to find the smallest substring that repeats to form the entire string.

Python
s = "ababab"  # Initialize result as False res = False  # Iterate through possible lengths of substrings for i in range(1, len(s) // 2 + 1):     # Check if current length divides the string evenly     if len(s) % i == 0:         # Check if the substring repeats to form the string         if s[:i] * (len(s) // i) == s:             res = True             break print(res)   

Output
True 

Explanation:

  • We iterate through all possible lengths of substrings up to half the length of the string.
  • If the substring repeats to match the entire string, we set the result to True.

Using concatenation

Another simple method involves using find() function after concatenating the string with itself.

Python
s = "ababab"  # Check for repeating pattern using string concatenation res = (s + s).find(s, 1) != len(s) print(res)   

Output
True 

Explanation:

  • We concatenate the string with itself and check if the original string appears again, starting from the second character.
  • If it does, the string is made of repeated substrings.

Using string slicing and comparison

We can use slicing and comparison to check for a repeating pattern by dividing the string into smaller parts.

Python
s = "ababab"  # Assume no repetition initially res = False  # Check for repeating pattern by slicing for i in range(1, len(s)):     if len(s) % i == 0 and s[:i] * (len(s) // i) == s:         res = True         break print(res)   

Output
True 

Explanation:

  • We divide the string into smaller slices and check if they form the entire string through repetition.


Next Article
Check if String is Empty or Not - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Check for spaces in string
    Sometimes, while working with strings in Python, we need to determine if a string contains any spaces. This is a simple problem where we need to check for the presence of space characters within the string. Let's discuss different methods to solve this problem. Using 'in' operator'in' operator is on
    3 min read
  • How to Repeat a String in Python?
    Repeating a string is a simple task in Python. We can create multiple copies of a string by using built-in features. This is useful when we need to repeat a word, phrase, or any other string a specific number of times. Using Multiplication Operator (*):Using Multiplication operator (*) is the simple
    2 min read
  • Python - Check if variable is tuple
    We are given a variable, and our task is to check whether it is a tuple. For example, if the variable is (1, 2, 3), it is a tuple, so the output should be True. If the variable is not a tuple, the output should be False. Using isinstance()isinstance() function is the most common and Pythonic way to
    2 min read
  • Check if String is Empty or Not - Python
    We are given a string and our task is to check whether it is empty or not. For example, if the input is "", it should return True (indicating it's empty), and if the input is "hello", it should return False. Let's explore different methods of doing it with example: Using Comparison Operator(==)The s
    2 min read
  • Python | Check if any String is empty in list
    Sometimes, while working with Python, we can have a problem in which we need to check for perfection of data in list. One of parameter can be that each element in list is non-empty. Let's discuss if a list is perfect on this factor using certain methods. Method #1 : Using any() + len() The combinati
    6 min read
  • Shrink List for Repeating Elements - Python
    We are given a list of elements that may contain repeated values. Our task is to shrink the list by ensuring that each repeated element appears only once while maintaining the order of their first occurrence. For example, if the input list is [2, 3, 2, 5, 3, 5], the output should be [2, 3, 5]. Using
    3 min read
  • Check for ASCII String - Python
    To check if a string contains only ASCII characters, we ensure all characters fall within the ASCII range (0 to 127). This involves comparing each character's value to ensure it meets the criteria. Using str.isascii()The simplest way to do this in Python is by using the built-in str.isascii() method
    2 min read
  • Python - Character repetition string combinations
    Given a string list and list of numbers, the task is to write a Python program to generate all possible strings by repeating each character of each string by each number in the list. Input : test_list = ["gfg", "is", "best"], rep_list = [3, 5, 2]Output : ['gggfffggg', 'iiisss', 'bbbeeesssttt', 'gggg
    3 min read
  • String Repetition and spacing in List - Python
    We are given a list of strings and our task is to modify it by repeating or adding spaces between elements based on specific conditions. For example, given the list `a = ['hello', 'world', 'python']`, if we repeat each string twice, the output will be `['hellohello', 'worldworld', 'pythonpython']. U
    2 min read
  • Python - Check if string starts with any element in list
    We need to check if a given string starts with any element from a list of substrings. Let's discuss different methods to solve this problem. Using startswith() with tuplestartswith() method in Python can accept a tuple of strings to check if the string starts with any of them. This is one of the mos
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences