I have this input [python]P (0, 2,+1) (2, 0, -1) (0, 4,+1) (4, 0, -1)[/python] and I would like to have it printed out this way [python][(0, 2, 1), (2, 0, -1), (0, 4, 1), (4, 0, -1)][/python]. However, due to the extra space in the input I ran into this error. Without making any change to the input, I wonder if anyone could advise? Thanks
[python]
algorithm_type_2 = list(eval(user_input_2))
File “”, line 1
(0,2,+1),(2,0,-1),(0,4,+1),(4,0,-1)
^
SyntaxError: invalid syntax
[/python]
By Longmen2022 via Discussions on Python.org at 05May2022 03:19:
I have this input [python]P (0, 2,+1) (2, 0, -1) (0, 4,+1) (4, 0,
-1)[/python] and I would like to have it printed out this way
[python][(0, 2, 1), (2, 0, -1), (0, 4, 1), (4, 0, -1)][/python].
However, due to the extra space in the input I ran into this error.
Without making any change to the input, I wonder if anyone could
advise? Thanks
[python]
algorithm_type_2 = list(eval(user_input_2))
File “”, line 1
(0,2,+1),(2,0,-1),(0,4,+1),(4,0,-1)
^
SyntaxError: invalid syntax
[/python]
That is not an extra space, it is an extra comma. I think you’ve simply
made a typing mistake.
please try very much to not use eval()? Particularly with input
received from a user, but it is generally a risky thing to do unless
you are extremely careful about composing the string you want
evaluated. xkcd: Exploits of a Mom (SQL, but applicable to any
evaluation situation.)
your technique for reading your input data and reforming it into
Python syntax is very rough - almost any change to it will make your
resulting string invalid.
Are your really in need of parser for brackets tuples, or is your
requirement a little different.
The most important skill for a programmer is to actually read the errors that they receive. We all write buggy code. The best programmer in the world probably writes more bugs in a day than you do in a month.
The difference is that good programmers can (usually) fix their bugs the instant they see them, because they read the error messages carefully.
If all else fails, and you really cannot change the input:
user_input2 = user_input2.replace(',,', ',')
to change double commas into single commas. But you should think about why you have double commas in user_input2, and if possible, prevent them from being entered in the first place.
And I agree with Cameron: you shouldn’t be using eval unless you really, really, really know what you are doing.