python编程开发之类型转换convert实例分析

本文实例讲述了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:

#类型转换#convert#convert to intprint('int()默认情况下为:', int())print('str字符型转换为int:', int('010'))print('float浮点型转换为int:', int(234.23))#十进制数10,对应的2进制,8进制,10进制,16进制分别是:1010,12,10,0xaprint('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 longprint('int浮点型转换为int:', int(23))#convert to floatprint('float()默认情况下为:', float())print('str字符型转换为float:', float('123.01'))print('int浮点型转换为float:', float(32))#covert to complexprint('创建一个复数(实部+虚部):', complex(12, 43))print('创建一个复数(实部+虚部):', complex(12))#convert to strprint('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 liststrs = 'hongten'print('序列strs转换为list:', list(strs))#covert to tuple print('列表list转换为tuple:', tuple(lists))#字符和整数之间的转换#char coverted to intprint('整数转换为字符chr:', chr(67))print('字符chr转换为整数:', ord('C'))print('整数转16进制数:', hex(12))print('整数转8进制数:', oct(12))

登录后复制

运行效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>> int()默认情况下为: 0str字符型转换为int: 10float浮点型转换为int: 234int('0xa', 16) = 10int('10', 10) = 10int('12', 8) = 10int('1010', 2) = 10int浮点型转换为int: 23float()默认情况下为: 0.0str字符型转换为float: 123.01int浮点型转换为float: 32.0创建一个复数(实部+虚部): (12+43j)创建一个复数(实部+虚部): (12+0j)str()默认情况下为: float字符型转换为str: 232.33int浮点型转换为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程序设计有所帮助。

立即学习“Python免费学习笔记(深入)”;

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2534933.html

(0)
上一篇 2025年3月5日 22:11:02
下一篇 2025年2月23日 23:52:36

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论