0

In my program, I would like to split the string "a*h+b=c" at the signs *, +, =, so the resulting list should look like ['a','h','b','c']. I have tried using the split command, but it can't split at multiple charactars. Is there a simple command to do this and if not,p plese let me know, or share some ideas. Thanks

  • 3
    Does this answer your question? [Split Strings into words with multiple word boundary delimiters](https://stackoverflow.com/questions/1059559/split-strings-into-words-with-multiple-word-boundary-delimiters) – mackorone Jan 06 '21 at 06:53

2 Answers2

1

A simple regex will work

import re
string = "a*h+b=c"
re.split('\W+', string)
['a', 'h', 'b', 'c']

You can also add custom delimiters in [] and the code will look like:

import re
s = "a*h+b=c"
re.split('[*+= ]',s)

\w+ matches 1 or more word characters

anik jha
  • 139
  • 1
  • 9
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
0

If you do not like to use re and not familiar with re module and REGEX. Then use my answer

string="a*h+b=c"
char_to_split=['*','+','=']
my_list=[]
for ch in string:
    if ch not in char_to_split:
        my_list.append(ch)

print(my_list)

prints ['a', 'h', 'b', 'c']

Hopes helpful!

Udhaya
  • 335
  • 3
  • 12