本文实例讲述了python编程开发之类型转换convert。分享给大家供大家参考,具体如下:
在python的开发过程中,难免会遇到类型转换,这里给出常见的类型转换demo:
int(x [,base ]) 将x转换为一个整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串
下面是我做的demo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#类型转换
#convert
#convert to int
print ( 'int()默认情况下为:' , int ())
print ( 'str字符型转换为int:' , int ( '010' ))
print ( 'float浮点型转换为int:' , int ( 234.23 ))
#十进制数10,对应的2进制,8进制,10进制,16进制分别是:1010,12,10,0xa
print ( 'int(\'0xa\', 16) = ' , int ( '0xa' , 16 ))
print ( 'int(\'10\', 10) = ' , int ( '10' , 10 ))
print ( 'int(\'12\', 8) = ' , int ( '12' , 8 ))
print ( 'int(\'1010\', 2) = ' , int ( '1010' , 2 ))
#convert to long
print ( 'int浮点型转换为int:' , int ( 23 ))
#convert to float
print ( 'float()默认情况下为:' , float ())
print ( 'str字符型转换为float:' , float ( '123.01' ))
print ( 'int浮点型转换为float:' , float ( 32 ))
#covert to complex
print ( '创建一个复数(实部+虚部):' , complex ( 12 , 43 ))
print ( '创建一个复数(实部+虚部):' , complex ( 12 ))
#convert to str
print ( 'str()默认情况下为:' , str ())
print ( 'float字符型转换为str:' , str ( 232.33 ))
print ( 'int浮点型转换为str:' , str ( 32 ))
lists = [ 'a' , 'b' , 'e' , 'c' , 'd' , 'a' ]
print ( '列表list转换为str:' , ''.join(lists))
#covert to list
strs = 'hongten'
print ( '序列strs转换为list:' , list (strs))
#covert to tuple
print ( '列表list转换为tuple:' , tuple (lists))
#字符和整数之间的转换
#char coverted to int
print ( '整数转换为字符chr:' , chr ( 67 ))
print ( '字符chr转换为整数:' , ord ( 'C' ))
print ( '整数转16进制数:' , hex ( 12 ))
print ( '整数转8进制数:' , oct ( 12 ))
|
运行效果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
Python 3.3 . 2 (v3. 3.2 :d047928ae3f6, May 16 2013 , 00 : 03 : 43 ) [MSC v. 1600 32 bit (Intel)] on win32
Type "copyright" , "credits" or "license()" for more information.
>>> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = RESTART = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
>>>
int ()默认情况下为: 0
str 字符型转换为 int : 10
float 浮点型转换为 int : 234
int ( '0xa' , 16 ) = 10
int ( '10' , 10 ) = 10
int ( '12' , 8 ) = 10
int ( '1010' , 2 ) = 10
int 浮点型转换为 int : 23
float ()默认情况下为: 0.0
str 字符型转换为 float : 123.01
int 浮点型转换为 float : 32.0
创建一个复数(实部 + 虚部): ( 12 + 43j )
创建一个复数(实部 + 虚部): ( 12 + 0j )
str ()默认情况下为:
float 字符型转换为 str : 232.33
int 浮点型转换为 str : 32
列表 list 转换为 str : abecda
序列strs转换为 list : [ 'h' , 'o' , 'n' , 'g' , 't' , 'e' , 'n' ]
列表 list 转换为 tuple : ( 'a' , 'b' , 'e' , 'c' , 'd' , 'a' )
整数转换为字符 chr : C
字符 chr 转换为整数: 67
整数转 16 进制数: 0xc
整数转 8 进制数: 0o14
>>>
|
希望本文所述对大家Python程序设计有所帮助。