Write a Python Program to Split Strings on Prefix Occurrence


This program is written in Python and it performs the following operations:

  • It creates a list of strings named "l" containing 5 elements.
  • It defines a variable "pref" with value "Tj".
  • It creates an empty list named "res".
  • It performs a for loop over the elements of the list "l".
  • For each element of the list "l", it checks if it starts with the value of "pref".
  • If the element starts with "pref", it appends the element as a list in "res".
  • If the element does not start with "pref", it appends the element to the last list of "res".
  • Finally, it prints the final list "res".

Source Code

l = ["TjC","TjCpp","TjPython","Java","tj"]
print("The original list is : ",l)
pref = "Tj"
 
res = []
for val in l:
	if val.startswith(pref):
		res.append([val])
	else:
		res[-1].append(val)
print("Prefix Split List : " + str(res))

Output

The original list is :  ['TjC', 'TjCpp', 'TjPython', 'Java', 'tj']
Prefix Split List : [['TjC'], ['TjCpp'], ['TjPython', 'Java', 'tj']]

Example Programs