0

I have this string below. It has no spaces.

"3.2+.4*5.67/6.145="

I would like for there to be spaces and to keep the floats intact. I'd also like to iterate over it to add elements to a string or a stack (eventual goal is to convert to postfix). So, I think this is the output that I need:

[3.2, +, .4, *, 5.67, /, 6.145, =]

Any ideas on how to do this?

The postfix output should eventually be this:

"3.2 .4 5.67 * 6.145 / +"
Yogesh Riyat
  • 129
  • 1
  • 7
  • You can simply split the string at the operators unless you have more complex cases, e.g., the number 1e-5 or 3**5. – Reti43 Apr 17 '21 at 21:26

2 Answers2

2

re.split() keeps capture groups (things wrapped in parenthesis):

import re
s = "3.2+.4*5.67/6.145="
[x for x in re.split("(\d*\.?\d*)", s) if x != '']

Edit: some more information for OP. The "(\d*\.?\d*)" part is saying

  • \d: match any integer (\d means integer in regex)
  • * match zero or more of the thing before me
  • \. match a literal period (since in regex . means any character)
  • ? match zero or one of the thing before me
  • \d: match any integer
  • * match zero or more of the thing before me

Wrapping the whole thing in parentheses is the trick. It is saying to capture the matched substring and then keep them. Usually, .split() gets rid of the matched delimiters.

user1717828
  • 7,122
  • 8
  • 34
  • 59
  • What if I just wanted to keep it as one string with spaces in between elements? "3.2 + .4 * 5.67 / 6.145 =" – Yogesh Riyat Apr 17 '21 at 22:29
  • How do I understand the notation inside the parenthesis: "(\d*\.?\d*)" – Yogesh Riyat Apr 17 '21 at 22:35
  • 1
    @YogeshRiyat I added some details around the explanation of the regex, but honestly if you really want to understand them you'll have to [learn them](https://github.com/ziishaned/learn-regex#what-is-regular-expression). Your first question is a separate question and you should open a new question for it. Basically, try running `"X".join(['apple','pear','banana'])` and go from there. – user1717828 Apr 17 '21 at 22:46
1

You can use regex:

import re
s="3.2+.4*5.67/6.145="
a=re.findall(r'(\d*\.\d*|[+,*,/,=])',s) #or a=[x for x in re.split(r'([+,*,/,=])', s)]
print(a)
>>>['3.2', '+', '.4', '*', '5.67', '/', '6.145', '=']
new_string=" ".join(a)
new_string
>>>"3.2 + .4 * 5.67 / 6.145 ="
zoldxk
  • 2,632
  • 1
  • 7
  • 29