Python | Split by repeating substring
Sometimes, while working with Python strings, we can have a problem in which we need to perform splitting. This can be of custom nature. In this, we can have a split in which we need to split by all the repetitions. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using * operator + len()
This is one of the way in this we can perform this task. In this, we compute the length of repeated string and then divide the list to obtain root and construct new list using * operator.
# Python3 code to demonstrate working of # Split by repeating substring# Using * operator + len() # initializing stringtest_str = "gfggfggfggfggfggfggfggfg" # printing original stringprint("The original string is : " + test_str) # initializing targetK = 'gfg' # Split by repeating substring# Using * operator + len()temp = len(test_str) // len(str(K))res = [K] * temp # printing result print("The split string is : " + str(res)) |
The original string is : gfggfggfggfggfggfggfggfg The split string is : ['gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg']
Method #2 : Using re.findall()
This is yet another way in which this problem can be solved. In this, we use findall() to get all the substrings and split is also performed internally.
# Python3 code to demonstrate working of # Split by repeating substring# Using re.findall()import re # initializing stringtest_str = "gfggfggfggfggfggfggfggfg" # printing original stringprint("The original string is : " + test_str) # initializing targetK = 'gfg' # Split by repeating substring# Using re.findall()res = re.findall(K, test_str) # printing result print("The split string is : " + str(res)) |
The original string is : gfggfggfggfggfggfggfggfg The split string is : ['gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg']


.png)
