Converting a string to a tuple in python

后端 未结 3 756
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 04:13

Okay, I have this string

tc=\'(107, 189)\'

and I need it to be a tuple, so I can call each number one at a time.

print(tc[         


        
相关标签:
3条回答
  • 2021-01-15 04:51

    All you need is ast.literal_eval:

    >>> from ast import literal_eval
    >>> tc = '(107, 189)'
    >>> tc = literal_eval(tc)
    >>> tc
    (107, 189)
    >>> type(tc)
    <class 'tuple'>
    >>> tc[0]
    107
    >>> type(tc[0])
    <class 'int'>
    >>>
    

    From the docs:

    ast.literal_eval(node_or_string)

    Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

    0 讨论(0)
  • 2021-01-15 04:54

    Use ast.literal_eval():

    >>> import ast
    >>> tc='(107, 189)'
    >>> tc_tuple = ast.literal_eval(tc)
    >>> tc_tuple
    (107, 189)
    >>> tc_tuple[0]
    107
    
    0 讨论(0)
  • 2021-01-15 04:56

    You can use the builtin eval, which evaluates a Python expression:

    >>> tc = '(107, 189)'
    >>> tc = eval(tc)
    >>> tc
    (107, 189)
    >>> tc[0]
    107
    
    0 讨论(0)
提交回复
热议问题