python中的str()與eval函數


author:headsen chen  

date:2018-04-09   10:48:22

 

eval函數是把str轉化成list、dict、tuple

str函數把list,dict,tuple轉為為字符串

----------------------------------------------------------------
# 字符串轉換成列表
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
print(type(a))
b = eval(a)
print(b,type(b))


<class 'str'>
([1, 2], [3, 4], [5, 6], [7, 8], [9, 0]) <class 'tuple'>

 

------------------------------------------------------------- 

# 字符串轉換成字典

a = "{1: 'a', 2: 'b'}"
print(type(a))
b = eval(a)
print(b,type(b))

<class 'str'>
{1: 'a', 2: 'b'} <class 'dict'>

 

----------------------------------------------------------

# 字符串轉換成元組
a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
print(type(a))
b=eval(a)
print(b,type(b))

<class 'str'>
([1, 2], [3, 4], [5, 6], [7, 8], [9, 0]) <class 'tuple'>


免責聲明!

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



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