Jalo Jalo - 19 days ago 10
Python Question

extract list or tuple inside string

I am getting input from an external device connected via Ethernet, and it is passing several values of string type e.g.

value = '(2,2)\n'
. I would like to assign these values to a list or tuple variable e.g.
final_value = (2,2)
.
The code I am using is the following:

import socket
sock = socket.socket()
value =sock.recv(buffersize=2048)
formatted_value = eval(value)


I read that the eval function I am using at this moment to get the list is not a very safe approach, as the external device could pass a dangerous script. So, I would like to know if there is any alternative, similar to the function int(), which can be used to get an integer from a string.

Answer

Use ast module for a safer eval

import ast
formatted_value = ast.literal_eval(value)