python的数字与字符串相互转换 |
您所在的位置:网站首页 › python字符串转换成整数型 › python的数字与字符串相互转换 |
字符串转数字 经常在处理文本时,比如memory初始化文件,或者解析log中的数据做运算时,会用到字符串转数字。 最常用的就是int(str, base=10),默认是处理十进制字符串,比如: s = '10' n = int(s) print(type(n)) # print(n) # 10那其它进制呢? # 二进制 print(int('10', 2)) # 2 # 十六进制 print(int('a', 16)) # 10 # 前缀和大小写不重要 print(int('0xa', 16)) # 10 print(int('0Xa', 16)) # 10 print(int('0XA', 16)) # 10带小数的字符串转数字的方法: print(float('12.101')) # 12.101数字转字符串这个可以简单理解成格式化输出,用字符串的format函数就行了。在python的数据类型(三):字符串中已经有过format函数的介绍。我们再举一些例子: print("{:b}".format(10)) # 1011 print("{:#b}".format(10)) # 0b1011 print("{:x}".format(10)) # a print("{:#x}".format(10)) # 0xa # 十六进制的大写形式(二进制没有大写的说法) print("{:X}".format(10)) # A print("{:#X}".format(10)) # 0XA前面补0的方法: print("{:0>4x}".format(10)) # 000a # 同时补0和加0x print("0x{:0>4x}".format(10)) # 0x000aformat格式定义详见: https://docs.python.org/3/library/string.html#formatspec 小数格式化成字符串的方法: print("{:f}".format(12.101)) # 12.101000 print("{:.2f}".format(12.101)) # 小数点后保存两位关于同时加0x和补0的坑当按照官方文档,同时使用#和宽度时,实际出来的结果跟想像的不一样,如下: >>> print("{:0>#8x}".format(10)) 000000xa >>> print("{:0>+#08x}".format(10)) 0000+0xa实际是先加0x,再对整体补0。 但是python提供了=代替>来应对这种异常。 '=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width. 所以,解决办法是: print("{:0=#8x}".format(10)) #0x00000a但有没有发现少了两个0?各位在使用时要留意,以免掉坑里。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |