python 数字与字符串转换

python 数字与字符串转换
python2

在这里插入图片描述

例子程序:

数字转字符串

#!/usr/bin/python
#-*- coding:utf-8 -*-

if __name__ == "__main__":

    a = 64

    print 'type(a)=', type(a)
    print 'a=', a

    print
    b = oct(a)

    print 'type(b),', type(b)
    print 'b=', b

    c = hex(a)

    print 'type(c),', type(c)
    print 'c=', c

    d = bin(a)

    print 'type(d),', type(d)
    print 'd=', d




结果:

C:\Python27\python.exe E:/python/work/thread_t1/number_test.py
type(a)= <type 'int'>
a= 64

type(b), <type 'str'>
b= 0100
type(c), <type 'str'>
c= 0x40
type(d), <type 'str'>
d= 0b1000000

Process finished with exit code 0

字符串转数字

#!/usr/bin/python
#-*- coding:utf-8 -*-

if __name__ == "__main__":

    a = '64'

    print 'type(a)=', type(a)
    print 'a=', a

    print
    b = int(a)

    print 'type(b),', type(b)
    print 'b=', b

    print

    c = '40'

    print 'type(c),', type(c)
    print 'c=', c

    d = int(c, 16)

    print 'type(d),', type(d)
    print 'd=', d

    print

    e = '100'

    print 'type(e),', type(e)
    print 'e=', e

    f = int(e, 8)

    print 'type(f),', type(f)
    print 'f=', f

    print
    g = '1000000'

    print 'type(g),', type(g)
    print 'g=', g

    h = int(g, 2)

    print 'type(h),', type(h)
    print 'h=', h



log 为:

C:\Python27\python.exe E:/python/work/thread_t1/number_test.py
type(a)= <type 'str'>
a= 64

type(b), <type 'int'>
b= 64

type(c), <type 'str'>
c= 40
type(d), <type 'int'>
d= 64

type(e), <type 'str'>
e= 100
type(f), <type 'int'>
f= 64

type(g), <type 'str'>
g= 1000000
type(h), <type 'int'>
h= 64

Process finished with exit code 0

在这里插入图片描述

在这里插入图片描述
•ord是unicode ordinal的缩写,即编号
•chr是character的缩写,即字符
•ord和chr是互相对应转换的.
•但是由于chr局限于ascii,长度只有256,于是又多了个unichr.


版权声明:本文为wowocpp原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。