欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python string与list,tuple,dict相互转换

程序员文章站 2024-03-23 17:55:04
...
#转字符串方法str()
#字符串转list,tuple,dict方法eval()
a = [1,2,3]
b = (1,2,3)
c = {1:1,2:2,3:3}
print("a",type(a),a)
print("b",type(b),b)
print("c",type(c),c)
a_s = str(a)
b_s = str(b)
c_s = str(c)
print("a_s",type(a_s),a_s)
print("b_s",type(b_s),b_s)
print("c_s",type(c_s),c_s)
a_s_l = eval(a_s)
b_s_t = eval(b_s)
c_s_d = eval(c_s)
print("a_s_l",type(a_s_l),a_s_l)
print("b_s_t",type(b_s_t),b_s_t)
print("c_s_d",type(c_s_d),c_s_d)

输出结果

a <class 'list'> [1, 2, 3]
b <class 'tuple'> (1, 2, 3)
c <class 'dict'> {1: 1, 2: 2, 3: 3}
a_s <class 'str'> [1, 2, 3]
b_s <class 'str'> (1, 2, 3)
c_s <class 'str'> {1: 1, 2: 2, 3: 3}
a_s_l <class 'list'> [1, 2, 3]
b_s_t <class 'tuple'> (1, 2, 3)
c_s_d <class 'dict'> {1: 1, 2: 2, 3: 3}