字符串中的字典取出value值(eval 使用及介紹)


eval:eval() 函數用來執行一個字符串表達式,並返回表達式的原始值。

例如:有個字符串 A="{'value': 'hello'}"

想要輸出該字符串的value值,應該怎么辦。

如果僅僅是一個字典的話直接取dict['key']就可以輕松取出來,但是在字符串中我們就必須想辦法把字符串轉化成字典。這時候eval函數就該閃亮登場了。

代碼如下:

>>> A="{'value': 'hello'}"
>>> B=eval(A)
>>> B
{'value': 'hello'}

 

 

此時在字典情況下想取出值就輕而易舉了!

>>> B['value']

Python eval 函數妙用

作者博文地址:https://www.cnblogs.com/liu-shuai/

eval

  功能:將字符串str當成有效的表達式來求值並返回計算結果。

  語法: eval(source[, globals[, locals]]) -> value

  參數:

    source:一個Python表達式或函數compile()返回的代碼對象

    globals:可選。必須是dictionary

    locals:可選。任意map對象

  實例展示:

可以把list,tuple,dict和string相互轉化。
#################################################
字符串轉換成列表
>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>>type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> type(b)
<type 'list'>
#################################################
字符串轉換成字典
>>> a = "{1: 'a', 2: 'b'}"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
{1: 'a', 2: 'b'}
>>> type(b)
<type 'dict'>
#################################################
字符串轉換成元組
>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
>>> type(b)
<type 'tuple'>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM