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.
CodePudding user response:
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', '$']
CodePudding user response:
Another regex approach giving the same result is:
split_sample = re.split(r"(\ |=|\$)", sample)[:-1]
The [:-1] is to remove the final empty string.
CodePudding user response:
"""
Given the equation b123 xyz=1 z1$, break it down
into a list of variables and operators
"""
operators = [' ', '-', '/', '*', '=']
equation = 'b123 xyz=1 z1$'
equation_by_variable_and_operator = []
text = ''
for character in equation:
if character not in operators:
text = text character
elif character in operators and len(text):
equation_by_variable_and_operator.append(text)
equation_by_variable_and_operator.append(character)
text = ''
# For the final variable
equation_by_variable_and_operator.append(text)
print(equation_by_variable_and_operator)
Output
['b123', ' ', 'xyz', '=', '1', ' ', 'z1$']