字符串&&列表&&字典&&元组&&集合 相互转换详解

1.eval() 函数   

定义:eval() 函数用来执行一个字符串表达式,并返回表达式的值。 简单的描述就是去掉引号,只执行表达式

本质:执行表达式的本质 如果存在运算则返回表达式的值,如果不存在运算则相当于去掉‘’ 取表达式 

作用:

1. 将字符串数据类型转换成其它类型     把字符串类型的 列表、字典、元组,集合转换为表达式的类型

a = '''[1,'b',2]'''  # 这里纯数字可套单引号,一旦包含字符就只能是三引号???
# a = '''{'a':1,'b':'eee'}'''
s = eval(a)
print(s)
print(type(s))

>>  [1, 'b', 2]
>>  <class 'list'>

   

2. 执行字符串表达式 返回表达式的值

x = 7
y = eval( '3 * x' )   
print(y)

>> 21

2.数据类型的相互转换 (str list tuple dict set)

1.字符串转换为其他类型

###字符串转列表
s = 'hello python'
li = list(s)
print li
print type(s)
print type(li)

>>  ['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n'] 
>>  <type 'str'> 
>>  <type 'list'>

### 字符串转为元组
s = 'hello python'
t = tuple(s)
print t
print type(s)
print type(t)

>>  ('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>  <type 'str'>
>>  <type 'tuple'>

### 字符串转集合
s = 'hello python'
set1 = set(s)
print set1
print type(s)
print type(set1)

>> set([' ', 'e', 'h', 'l', 'o', 'n', 'p', 't', 'y'])    注意:元组 套列表 无序    问:如何把字符串转换为无序列表
>> <type 'str'>
>> <type 'set'>


### 字符串转字典   eval()函数  已阐述

2.列表转为其它类型

###列表转化为字符串  直接转换类型
li=["hello",1,1+3j]
print type(li)
s=str(li)
print s
print type(s)

>>  <type 'list'>
>>  ['hello', 1, (1+3j)]
>>  <type 'str'>

### 列表转换为字符串  拼接字符串
l1=('a','b','c')
s = ''.join(l1)print(s)print(type(s))

### 列表转化为元组 tuple(l1) ### 列表转化为字典 li1 = ['NAME', 'AGE', 'gender'] li2 = ['redhat', 10, 'M'] d= dict(zip(li1,li2)) print d,type(d) ###列表转集合 l1=['a',1,'c'] print(set(l1)) print(type(set(l1))) >> {1, 'c', 'a'} >> <class 'set'>

3.元组转换为其它类型

###元组转化成字符串  直接转化类型
t=("hello",1,1+3j,1,"2","3","2",3)
print type(t)
s=str(t)
print s
print type(s)

>> <type 'tuple'>
>>  ('hello', 1, (1+3j), 1, '2', '3', '2', 3)
>>  <type 'str'>

###元组转化为列表
l1=list(t)
###元组转化为字典
t1 = ('NAME', 'AGE', 'gender')
t2 = ('redhat', 10, 'M')
d= dict(zip(t1,t2))
print d,type(d)

4. 字典转换为其它类型   

   1.只能将( d.keys(), d.values, for i in  dict  dict容器中装的是keys )转换为其它格式

   2. 只能转换keys 和 vaues (列表)

   3. 不能通过 dict(l1)   直接强转类型   可以用两个列表,元组或集合  dict(zip(l1,l2))

5. 集合转换为其它类型

### 集合转化为字符串 
li={"hello",1,1+3j]}
print type(li)
s=str(li)
print s
print type(s)

### 结合转换为字符串  拼接字符串
t1={'a','b','c')}
s = ''.join(l1)
print(s)
print(type(s))

### 集合转化为元组 列表
tuple(t1)  list(t1)

### 列表转化为字典
t1 = {'NAME', 'AGE', 'gender'}
t2 = {'redhat', 10, 'M'}
d= dict(zip(li1,li2))
print (d,type(d))

猜你喜欢

转载自www.cnblogs.com/bigbox/p/11829614.html