Pretty simply question but giving me some trouble:
I have
"('A', 'Open')" # type = str
and would like:
('A','Open') # type = tuple
Have tried using .split(), and just converting the whole thing to tuple(str) with no success.
Pretty simply question but giving me some trouble:
I have
"('A', 'Open')" # type = str
and would like:
('A','Open') # type = tuple
Have tried using .split(), and just converting the whole thing to tuple(str) with no success.
There are two ways to achieve this, both parse the string as Python code.
The seemingly easier option is to use eval
.
The slightly more complicated, but better, option is to use ast.literal_eval
.
In Using python's eval() vs. ast.literal_eval()? everything has already been said why the latter is almost always what you really want. Note that even the official documentation of eval
says that you should use ast.literal_eval
instead.
How about this?
import re
m_s = "('A', 'Open')"
patt = r"\w+"
print(tuple(re.findall(patt, m_s)))
How about using regular expressions ?
In [1686]: x
Out[1686]: '(mono)'
In [1687]: tuple(re.findall(r'[\w]+', x))
Out[1687]: ('mono',)
In [1688]: x = '(mono), (tono), (us)'
In [1689]: tuple(re.findall(r'[\w]+', x))
Out[1689]: ('mono', 'tono', 'us')
In [1690]: x = '(mono, tonous)'
In [1691]: tuple(re.findall(r'[\w]+', x))
Out[1691]: ('mono', 'tonous')
Shortest is do
eval("('A','Open')") #will return type as tuple
eval() evaluates and executes string as python expression