Method # 1: Using a comprehension list + brute force
We can accomplish this task using selective slicing and brute force. This is a naive method for finding a string where we are trying to get the root string by splitting the string again.
# Python3 code to demonstrate how it works # Check if the line is repeated # Using brute force comprehension list # initialization string test_str = "GeeksforGeeksGeeksforGeeksGeeksforGeeks" # print the original line print ( "The original string is:" + test_str) < / code> # using comprehension list + brute force # Check if the line is repeated res = None for i in range ( 1 , len (test_str) / / 2 + 1 ): if ( not len ( test_str) % len (test_str [ 0 : i]) and test_str [ 0 : i] * ( len (test_str) / / len (test_str [ 0 : i])) = = test_str): res = test_str [ 0 : i] # print result print ( "The root substring of string:" + res) |
Output:
The original string is: GeeksforGeeksGeeksforGeeksPython.Engineering The root substring of string: Python.Engineering
Method # 2: Using list slicing + find()
This problem can also be solved by the fact that we can search for the root string after adding the string and checking the root string in that string, except for the last and first character, which is a repeated string.
Doesn’t work for line length "2.
# Python3 code to demonstrate how it works # Check if the line is repeated # Using list slicer + find () # initialization string test_str = "GeeksforGeeksGeeksforGeeksGeeksforGeeks" # print the original line print ( "The original string is:" + test_str) # using list slicing + find () # Check if the line is repeated res = None temp = (test_str + test_str) .find (test_str, 1 , - 1 ) if temp! = - 1 : res = test_str [: temp] # print result print ( "The root substring of string:" + res) |
Output:
The original string is: GeeksforGeeksGeeksforGeeksPython.Engineering The root substring of string: Python.Engineering
Python | Check if the line is repeated Python functions: Questions
Python | Check if the line is repeated repeat: Questions