Converting Between Simple Types

    除了 string formating 特性,Python还提供了许多函数用于 numerical 和 string 类型之间的转换。

1、Converting to numerical types

    函数 int、long、float、complex,以及ord 都是将数据转换成 numerical 类型。

(1)int (x[, radix])

    使用一个 string 和一个可选的 base,将一个 number 或 string 转换成一个 integer:

>>> int(‘15’)

15

>>> int(‘15’,16) # In hexadecimal, sixteen is written “10”

21

    待转换的字符串必须是一个合法的整数,转换字符串 3.5 就会失败。int 函数可以将其他 numbers 转换成 integers:

>>> int(3.5)

3

>>>int(10L)

10

    int 函数会去掉一个 number 的小数部分。要得到 最接近的 integer,就要用 round 函数。

(2)long(x[, radix])

    可以将一个字符串或另一个 number转换成一个 long integer,也可以包含一个base:

>>> long('125')

125L

>>> long(17.6)

17L

>>> long('1E', 16)

30L

(3)float(x)

>>> float(12.1)

12.1

>>> float(10L)

10.0

>>> int(float("3.5")) # int("3.5") is illegal

3

The exception is with complex numbers; use the abs function to “convert” a

complex number to a floating-point number.

(4)round(num[,digits])

    四舍五入一个浮点数为一个拥有指定小数位的一个 number:

>>> round(123.5678, 3)

123.568

>>> round(123.5678)

124.0

>>> round(123.4)

123.0

(5)complex(real[, imaginary])

    可以将一个字符串或 number转成一个复数,它还带一个可选的imaginary部分,如果没有提供的话:

>>> complex('2+5j')

(2+5j)

>>> complex('2')

(2+0j)

>>> complex(6L, 3)

(6+3j)

(6)ord(ch)

    参数是一个字符,返回的是该字符对应的 ASCII 或 Unicode值

>>> ord(u'a')

97

>>> ord('b')

98

2、Converting to strings

    以下函数将 numbers 转换成 字符串。

(1)chr (x) and unichr (x)

     将参数代表的 ASCII 或 Unicode 值 转成一个字符:

>>> chr(98)

‘b’

(2)oct (x) and hex (x)

    将 numbers 转换成八进制和16进制字符串表示:

>>> oct(123)

'0173'

>>> hex(123)

'0x7b'

(3)str (obj)

    返回对象的一个可打印的字符串版本值:

>>> str(5)

'5'

>>> str(5.5)

‘5.5’

>>> str(3+2j)

‘(3+2j)’

    当使用 print 语句时,Python会就会调用该函数。

(4)repr(obj)

    repr 和 str 类似,except that it tries to return a string version of the object that is valid Python syntax。对于简单的数据类型,它俩的输出常常是一样的。 

它的一个简写方式是将待转换的对象放到``号之间。

>>> a = 5

>>> ‘Give me ‘ + a # Can’t add a string and an integer!

Traceback (innermost last):

File “<interactive input>”, line 1, in ?

TypeError: cannot add type “int” to string

>>> ‘Give me ‘ + `a` # Convert to a string on-the-fly.

‘Give me 5’

    从 2.1 版开始,str 和 repr 会原样显示 newlines 和 其他转义序列,而不是显示它们的 ASCII code:

>>> 'Hello\nWorld'

'Hello\nWorld'

    当以交互式方式使用 Python interpreter, Python 会调用 repr 来显示对象。你可以让它使用一个不同的函数,那就要先修改 sys.displayhook 的值:

>>> 5.3

5.2999999999999998  # The standard representation is ugly.

>>> def printstr(s):

...   print str(s)

>>> import sys

>>> sys.displayhook = printstr

>>> 5.3

5.3  # A more human-friendly format

The sys.displayhook feature is new in Python 2.1.

猜你喜欢

转载自zsjg13.iteye.com/blog/2230326