I have a string that contains numbers and math symbols, such as: data = "1678-156"
or data = "354+45"
. How can I turn this into a list like so: dataList = ["1678","-","156"]
or dataList = ["354","+","45"]
. Any easy way to do this?
Asked
Active
Viewed 98 times
-1

ThePyGuy
- 17,779
- 5
- 18
- 45

Collin Meyer
- 13
- 2
-
There's a lot of possible corner cases for this. For example, can there be more than one operator? Can there be whitespace? Can there be alphabets? Can there be decimals? Or is it just digits and one operator? Add some more details/test cases for us to give a robust solution – Shubham Periwal May 12 '21 at 00:03
-
What happened when you tried putting `python split string` into a search engine? – Karl Knechtel May 12 '21 at 00:15
-
Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune May 12 '21 at 00:23
2 Answers
0
You could use re.findall
:
data = "1678-156"
parts = re.findall(r'[*/+-]|\d+(?:\.\d+)?', data)
print(parts) ['1678', '-', '156']
This answer assumes that the only components of your formula would be either basic arithmetic symbols */+-
or decimal/whole numbers.

Tim Biegeleisen
- 502,043
- 27
- 286
- 360
0
import re
data = "1678-156"
arr = re.split('(\W)', data)

Baran Bursalı
- 360
- 1
- 7
-
can add `data.replace(' ','')` in the beginneing or `arr = [ele.strip() for ele in arr if len(ele.strip()) > 0]` in the end, if there could be spaces in the string and want to get rid of those. Because otherwise spaces will show up as array elements too. – Shivam Agrawal May 12 '21 at 00:26