I want to create a list given a string such as ‘b123+xyz=1+z1$’ so that the list equals [‘b123’, ‘+’, ‘xyz’, ‘=’, ‘1’, ‘+’, ‘z1’, ‘$’]
Without spaces or a single repeating pattern, I do not know how to split the string into a list.
I tried creating if statements in a for loop to append the string when it reaches a character that is not a digit or letter through isdigit and isalpha but could not differentiate between variables and digits.
Advertisement
Answer
You can use a regular expression to split your string. This works by using positive lookaheads and look behinds for none word chars.
import re sample = "b123+xyz=1+z1$" split_sample = re.split("(?=W)|(?:(?<=W)(?!$))", sample) print(split_sample)
OUTPUT
['b123', '+', 'xyz', '=', '1', '+', 'z1', '$']