0

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.

thomas.mac
  • 1,236
  • 3
  • 17
  • 37

4 Answers4

2

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.

Graipher
  • 6,891
  • 27
  • 47
  • 1
    `ast.literal_eval` is _slightly more complicated_ than `eval`, how so? – vishes_shell Jan 04 '19 at 08:49
  • 1
    @vishes_shell: You need to add an import (albeit from the standard library). I did not say it was a lot more complicated... It might also be slightly slower in evaluating the string, since it first performs some checks. – Graipher Jan 04 '19 at 08:50
0

How about this?

import re

m_s = "('A', 'Open')"
patt = r"\w+"
print(tuple(re.findall(patt, m_s)))
Nafeez Quraishi
  • 5,380
  • 2
  • 27
  • 34
0

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')
0

Shortest is do

eval("('A','Open')") #will return type as tuple

eval() evaluates and executes string as python expression

Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40