python学习笔记,整形,字符串

来源:互联网 发布:dnf老是网络中断2016 编辑:程序博客网 时间:2024/05/01 22:08


字符串转换成整形

import string
a="12345"

#转换成int
string.atoi(a)

#也可以,不用区分int和long。
int(a)

#不过如果你的数字太长 还是转换成 long
string.atol()

二进制、十六进制与十进制之间的转换
  1. def Binary2Decimal(bin_num):
  2.     """ Return the decimal representation of bin_num
  3.     
  4.         This actually uses the built-in int() function, 
  5.         but is wrapped in a function for consistency """
  6.     return int(bin_num, 2)
  7. def hex2Decimal(bin_num):
  8.     return int(bin_num, 16)
  9. def Decimal2Binary(dec_num):
  10.     """ Return the binary representation of dec_num """
  11.     if dec_num == 0: return ''
  12.     head, tail = divmod(dec_num, 2)
  13.     return Decimal2Binary(head) + str(tail)