简体   繁体   中英

How can i convert a string to tuple in python

i have read a string from csv_file given below

"('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]})," 

when i iterate over it, I get each character as:

('(', "'", 'W', 'h', 'o', ' ', 'i', 's', ' ', 'S', 'h', 'a', 'k', 'a', ' ', 'K', 'h', 'a', 'n', '?', "'", ',', '{', "'", 'e', 'n', 't', 'i', 't', 'i', 'e', 's', "'", ':', ' ', '[', '(', '7', ',', ' ', '1', '7', ',', ' ', "'", 'P', 'E', 'R', 'S', 'O', 'N', "'", ')', ']', '}', ')', ',') 

but i need it to be stored in tuple form so when i iterate over it i can get output as given below

 Who is Shaka Khan?

{'entities': [(7, 17, 'PERSON')]} 

how can i do this in python?

Use ast.literal_eval to convert the string to a tuple.

>>> s = "('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]})," 
>>> import ast
>>> t = ast.literal_eval(s)
>>> t[0]
('Who is Shaka Khan?', {'entities': [(7, 17, 'PERSON')]})
>>> t[0][0]
'Who is Shaka Khan?'
>>> t[0][1]
{'entities': [(7, 17, 'PERSON')]}

Optionally, you can convert it to a dict for easy access

>>> d = dict(ast.literal_eval(s))
>>> d['Who is Shaka Khan?']
{'entities': [(7, 17, 'PERSON')]}

Use literal_eval ,

In [87]: from ast import literal_eval

In [88]: literal_eval("('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]}),")
Out[88]: (('Who is Shaka Khan?', {'entities': [(7, 17, 'PERSON')]}),)

You can do it using ast.literal_eval

import ast
a = ast.literal_eval("('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]}),")
print(a[0][1])

OUTPUT

{'entities': [(7, 17, 'PERSON')]}

you have to use the tuple function, but it has to be a list beforehand

Example:

l = [4,5,6]
tuple(l)

RETURNS (4, 5, 6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM