How to parse problematic strings

I am working on a Scratch-Python handler and basically can do this with a parsing guru :)

I am working on handling input that is not entirely correct (my Scratch programmers may be under 7, so my person should get lines like this

"motor1" "12.5" "motor2" 80 "sonar8" "Pin11On" 

but they can easily end up like that when Scratch recruited extra "around the values โ€‹โ€‹of variables / names with spaces in them

 "motor 1" "12.345 " "motor2" 80 "sonar 8" "Pin 11 On" 

I am looking for the code to take above and return a new line

 motor1 12.345 motor2 80 sonar8 Pin11On 

Any suggestions that were received :)

Simon

+4
source share
1 answer
 In [52]: text = '"motor 1" "12.345 " "motor2" 80 "sonar 8" "Pin 11 On"' In [53]: import shlex In [54]: shlex.split(text) Out[54]: ['motor 1', '12.345 ', 'motor2', '80', 'sonar 8', 'Pin 11 On'] In [55]: [item.replace(' ','') for item in shlex.split(text)] Out[55]: ['motor1', '12.345', 'motor2', '80', 'sonar8', 'Pin11On'] In [56]: ' '.join([item.replace(' ','') for item in shlex.split(text)]) Out[56]: 'motor1 12.345 motor2 80 sonar8 Pin11On' 
+4
source

Source: https://habr.com/ru/post/1490362/


All Articles