目录

前言

本篇主要介绍Python的强制类型转换。

软件环境

  • 系统

    • UbuntuKylin 14.04
  • 软件
    • Python 2.7.3
    • IPython 4.0.0

Python数据类型的显式转换

数据类型的显示转换,也称为数据类型的强制类型转换,是通过Python的内建函数来实现的类型转换。

显式转换的多种类型

int(x [,base]) ⇒ 将x转换为一个十进制的整数
long(x [,base]) ⇒ 将x转换为一个十进制的长整数
float(x) ⇒ 将x转换为一个浮点数
str(object) ⇒ 转换为字符串
repr(object) ⇒ 转换为表达式字符串
eval(str) ⇒ 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(seq) ⇒ 将序列seq转换为一个元组
list(seq) ⇒ 将序列seq转换为一个列表
chr(x ) ⇒ 将一个整数转换为一个字符
unichr(x ) ⇒ 将一个整数转换为Unicode字符
ord(x ) ⇒ 将一个字符转换为它的整数值
hex(x ) ⇒ 将一个整数转换为一个十六进制字符串
oct(x ) ⇒ 将一个整数转换为一个八进制字符串

下面详细介绍一些常用的类型转换。

Non-String转换为String

str()函数

str(object=”) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
str()是最常用的转换为String的内建函数,可以接受任意对象,并将其转换为String类型。若object为String类型,则返回一个同类型的对象。
将List对象转换为String

  1. In [13]: li
  2. Out[13]: ['My', 'Name', 'Is', 'Jmilk']
  3. In [14]: strLi = str(li)
  4. In [15]: print strLi[0]
  5. [
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

将Tuple对象转换为String

  1. In [19]: tup = ('my','name','is','jmilk')
  2. In [20]: str(tup)
  3. Out[20]: "('my', 'name', 'is', 'jmilk')"
  4. In [22]: str(tup)[3]
  5. Out[22]: 'y'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

将Dictionary对象转换为String

  1. In [23]: dic = {'name':'Jmilk','age':23}
  2. In [24]: str(dic)
  3. Out[24]: "{'age': 23, 'name': 'Jmilk'}"
  4. In [25]: str(dic)[3]
  5. Out[25]: 'g'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

上面3个例子可以发现,在转换为String后无论是原来的特殊符号还是空格符都会成为String的元素之一。

repr()

repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
repr()函数的使用方法于str()函数类似,都是传入一个任意对象,再返回一个String类型对象,但两者却有着本质的区别。

str()和repr()的区别

主要的区别就在repr()支持eval(repr(object)) == object。str()函数的目标是一般用户的可读性,返回一个更适合人阅读的nice string。而repr()则返回一个更适合python解析器阅读的canonical strng,同时会返回Python解析器能够识别的数据细节,但这些细节对一般用户来说是多余的。而且repr()转换后的String对象可以通过求值运算eval()来还原到转换之前的对象,相比之下str()通常不需要eval()去处理。

  1. In [61]: name = ('My name is Jmilk\n')
  2. In [62]: print str(name)
  3. My name is Jmilk
  4. In [63]: print repr(name)
  5. 'My name is Jmilk\n'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

上面例子可以看出str()打印出来的字符串会更符合人的阅读习惯。

eval()

eval()函数,能够结合repr()函数将一个经过转换为Strng类型后的对象还原为转换之前的对象类型。同时eval()也被称为求值运算,可以将字符串str当成有效的表达式来求值并返回计算结果。

  1. In [64]: name = ('My name is Jmilk\n')
  2. In [65]: name1 = str(name)
  3. In [66]: name1
  4. Out[66]: 'My name is Jmilk\n'
  5. In [67]: name2 = repr(name)
  6. In [68]: name2
  7. Out[68]: "'My name is Jmilk\\n'"
  8. In [69]: eval(name1)
  9. File "<string>", line 1
  10. My name is Jmilk
  11. ^
  12. SyntaxError: invalid syntax
  13. In [70]: eval(name2)
  14. Out[70]: 'My name is Jmilk\n'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

eval(str(Object))可能会报错,无法还原为原来的对象型。而eval(repr(object))却可以还原,下面例子:

  1. In [81]: name = ('My','name','is','Jmilk\n')
  2. In [82]: repr(name)
  3. Out[82]: "('My', 'name', 'is', 'Jmilk\\n')"
  4. In [83]: eval(repr(name))
  5. Out[83]: ('My', 'name', 'is', 'Jmilk\n')
  6. In [84]: type(eval(repr(name)))
  7. Out[84]: tuple
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

总结:这是因为str()函数主要是为了让人能够更好的阅读其内容,而rper()除了转换为String类型外,还能够被Python解析器识别其数据细节,从而repr()转换后的字符串能够被当作有效表达式来处理。
注意:eval()函数最主要的功能是能够将字符串中有效的表达式进行计算并返回一个对象。如下:

  1. In [141]: sum = '100+10'
  2. In [142]: eval(sum)
  3. Out[142]: 110
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

Non-int转换为int

Int型的最大值仅与系统位数有关,32位:maxInt == 2**(32-1)-1 ; 64位:maxInt == 2**(64-1)-1。可以通过sys.maxint
来查看:

  1. In [42]: sys.maxint
  2. Out[42]: 9223372036854775807
  3. In [43]: 2**63-1
  4. Out[43]: 9223372036854775807L
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

在Python2.4x版本之后为Int增加了Long的隐式转换来防止数据范围溢出。
int(x[, base=10]) -> int or long
base:指定进制
x:通常为一个String
base指定了x的进制

Long转换为Int,使用自定义函数

当一个Long > sys.maxint(2**63-1)时,Long类型对象是无法转换为Int的。
Example:

  1. In [79]: int(2**63)
  2. Out[79]: 9223372036854775808L #仍为Long类型
  • 1
  • 2
  • 1
  • 2

下面使用一个自建的函数来实现当Long > sys.maxint时的Long到Int的强制类型转换。需要实现两个方面,一个是转换数值(不能超过maxint),另一个是转换类型为int。
转换数值

  1. In [130]: %pycat longToInt.py
  2. import sys
  3. def longToInt(value):
  4. if value > sys.maxint:
  5. return (value & sys.maxint)
  6. else:
  7. return value
  8. if __name__ == '__main__':
  9. number = 2**63
  10. result = longToInt(number)
  11. print 'number - sys.maxint = %s - %s = %s' % (number,sys.maxint,result)
  12. print 'result is %s,result type is %s;number type is %s' % (result,type(result),type(number))
  13. In [131]: run longToInt.py
  14. number - sys.maxint = 9223372036854775808 - 9223372036854775807 = 1
  15. result is 0,result type is <type 'long'>;number type is <type 'long'>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

上例:当number-sys.maxint=1时,将Long型number的数值转化为0输出。即当一个int类型的数值超过sys.maxint时,再将多余于的数值环回计数。以此类推,当number-sys.maxint=101时,Long型的number的环回计数为100。
需要注意的是:尽管数值是大于maxint,但是其数据类型仍然为long,可以使用int()函数将环回的数值转化为Int型,且只能在转换数值后才能成功额转换类型。
转换类型

  1. In [136]: %pycat longToInt.py
  2. import sys
  3. def longToInt(value):
  4. if value > sys.maxint:
  5. return (value & sys.maxint)
  6. else:
  7. return value
  8. if __name__ == '__main__':
  9. number = 2**63+100
  10. result = longToInt(number)
  11. print 'number - sys.maxint = %s - %s = %s' % (number,sys.maxint,result+1)
  12. print 'result is %s,result type is %s;number type is %s' % (result,type(int(result)),type(number))
  13. In [137]: run longToInt.py
  14. number - sys.maxint = 9223372036854775908 - 9223372036854775807 = 101
  15. result is 100,result type is <type 'int'>;number type is <type 'long'>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Float转换为Int

浮点型转为整型会进行向下取整。

  1. In [130]: int(10.9)
  2. Out[130]: 10
  • 1
  • 2
  • 1
  • 2

String转换为Int

  1. In [131]: int('0xa',16)
  2. Out[131]: 10
  3. In [132]: int('1010',2)
  4. Out[132]: 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

参数16表示’0xa’为16进制数,int()转换以后获得10进制数,若不指明’0xa’的进制,则会报错。

  1. In [133]: int('0xa')
  2. ValueError: invalid literal for int() with base 10: '0xa'
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

Non-long转化为long类型

long(x=0) -> long
long(x, base=10) -> long
生成一个long对象

  1. In [24]: long(10)
  2. Out[24]: 10L
  • 1
  • 2
  • 1
  • 2

也可以简单的实现:

  1. In [138]: num = 10L
  2. In [139]: type(num)
  3. Out[139]: long
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

Int转化为Long

int型转换为long型不需要强制类型转换,这就是相对的隐式类型转换,系统会在后台完成。在后面的博文中再作介绍。

Float转换为Long

向下取整

  1. In [27]: long(10.9)
  2. Out[27]: 10L
  • 1
  • 2
  • 1
  • 2

String转换为Long

  1. In [33]: long('0xa',16)
  2. Out[33]: 10L
  3. In [34]: long('1010',2)
  4. Out[34]: 10L
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

可以看出,Int与Long类型的数据非常类似,唯一的区别在于,Long类型的数据范围更加大。(Int)

Non-float转换为float

float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
可以接收Int和String类型参数,float()函数在连接数据库操作会被经常使用。当参数为String时,只能出现数字和一个点额任意组合,若出现多个点号,则会出现异常。

  1. In [194]: float(10)
  2. Out[194]: 10.0
  3. In [195]: float('100')
  4. Out[195]: 100.0
  5. In [199]: float('.1111')
  6. Out[199]: 0.1111
  7. In [204]: float('.98.')
  8. ---------------------------------------------------------------------------
  9. ValueError Traceback (most recent call last)
  10. <ipython-input-204-70a1a06c7ce5> in <module>()
  11. ----> 1 float('.98.')
  12. ValueError: invalid literal for float(): .98.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

Sequence转换为List

list(iterable) -> new list initialized from iterable’s items
使用迭代器中的元素生成一个新的列表

String转换为List

将字符串中的每一个字母作为列表中的一个元素,空格也算是一个元素

  1. In [137]: name = 'My name is Jmilk'
  2. In [138]: list(name)
  3. Out[138]:
  4. ['M',
  5. 'y',
  6. ' ',
  7. 'n',
  8. 'a',
  9. 'm',
  10. 'e',
  11. ' ',
  12. 'i',
  13. 's',
  14. ' ',
  15. 'J',
  16. 'm',
  17. 'i',
  18. 'l',
  19. 'k']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

Tuple转换为List

Tuple转换为List与String其实大同小异:

  1. In [1]: tup = ('My','name','is','Jmilk')
  2. In [2]: list(tup)
  3. Out[2]: ['My', 'name', 'is', 'Jmilk']
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

将Tuple对象中的每一个元素转换为List中的每个元素。

Sequence转换为Tuple

tuple(iterable) -> tuple initialized from iterable’s items
利用迭代器中的元素生成新的元组

String转换为Tuple

  1. In [5]: str = 'My name is Jmilk!'
  2. In [6]: tuple(str)
  3. Out[6]:
  4. ('M',
  5. 'y',
  6. ' ',
  7. 'n',
  8. 'a',
  9. 'm',
  10. 'e',
  11. ' ',
  12. 'i',
  13. 's',
  14. ' ',
  15. 'J',
  16. 'm',
  17. 'i',
  18. 'l',
  19. 'k',
  20. '!')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

类似String转换为List,空格任然算一个元素

List转换为Tuple

  1. In [9]: li
  2. Out[9]: ['My', 'name', 'is', 'Jmilk']
  3. In [10]: tuple(li)
  4. Out[10]: ('My', 'name', 'is', 'Jmilk')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

将List和Tuple复合数据类型转换为Dictionary

格式:dict([(key1,value1),..])

  1. In [144]: li = ['name','age','city']
  2. In [145]: tup = ('jmilk',23,'BJ')
  3. In [146]: zip(li,tup)
  4. Out[146]: [('name', 'jmilk'), ('age', 23), ('city', 'BJ')]
  5. In [148]: dict(zip(li,tup))
  6. Out[148]: {'age': 23, 'city': 'BJ', 'name': 'jmilk'}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Dictionary转换为List

相对的,Dictionary的键值对也能够转换为List和Tuple的复合数据类型。
D.items() -> list of D’s (key, value) pairs, as 2-tuples

  1. In [159]: dic
  2. Out[159]: {'age': 23, 'city': 'BJ', 'name': 'jmilk'}
  3. In [160]: dic.items()
  4. Out[160]: [('city', 'BJ'), ('age', 23), ('name', 'jmilk')]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

Int转换为字符char

chr(i) -> character
Return a string of one character with ordinal i; 0 <= i < 256.
以整数所对应的ASCII码来转换为Char,i属于[0,256)。

  1. In [174]: chr(65)
  2. Out[174]: 'A'
  3. In [175]: chr(97)
  4. Out[175]: 'a'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

最后

强制数据类型转换在编程过程中国非常常见,且在对内存、时间等运行环境要求严格的程序中尤为重要。

Jmilk

Python基本语法_强制数据类型转换的更多相关文章

  1. Python基本语法_基本数据类型_数值型详解

    目录 目录 软件环境 Python变量调用的过程 数值型 删除一个数值类型对象 布尔型 Bool 标准整型 Int 长整型 双精度浮点型 Float 复数 数值类型对象的内建功能函数 absNumbe ...

  2. C语言中强制数据类型转换(转)

    原文地址不详 字符型变量的值实质上是一个8位的整数值,因此取值范围一般是-128-127,char型变量也可以加修饰符unsigned,则unsigned char 型变量的取值范围是0-255(有些 ...

  3. Python基本语法_集合set/frozenset_内建方法详解

    目录 目录 前言 软件环境 可变集合Set set函数创建集合 创建空集合 集合元素的唯一性 集合推导式 set类型对象的内置方法 add增加一个元素 remove删除一个元素 pop随机删除并返回一 ...

  4. Python基本语法_输入/输出语句详解

    目录 目录 前言 输入 raw_input input raw_input 和 input 的区别 输出 print print 基本格式化输出 print复杂格式化输出 flags标志位 width ...

  5. Python基本语法_运算符详解

    目录 目录 前言 软件环境 身份运算符 算术运算符 比较运算符 位移运算符 自变运算符 位运算符 逻辑运算符 成员关系运算符 Python真值表 最后 前言 在前面的博文介绍了Python的数据结构之 ...

  6. Python基本语法_函数属性 & 参数类型 & 偏函数的应用

    目录 目录 前言 软件环境 Python Module的程序入口 函数的属性 Python函数的创建 函数的参数 必备参数 缺省参数 命名参数 不定长参数 匿名参数 偏函数的应用 前言 Python除 ...

  7. Python基本语法_异常处理详解

    目录 目录 异常 异常类型 异常处理 触发异常raise 传递异常 assert语句触发异常 捕获异常tryexceptelse 捕捉多个异常 tryfinally语句 自定义异常 withas触发异 ...

  8. python基础语法_闭包详解

    https://www.cnblogs.com/Lin-Yi/p/7305364.html 闭包有啥用??!! 很多伙伴很糊涂,闭包有啥用啊??还这么难懂!  3.1装饰器!!!装饰器是做什么的??其 ...

  9. 强制数据类型转换之Number类型

    ㈠强制类型转换 1.定义:指将一个数据类型强制转换为其他的数据类型    类型转换主要指,将其他的数据类型,转换为String ,Number, Boolean ㈡将其他的数据类型转换为Number ...

随机推荐

  1. Linux shell命令:用 !$ 防止误操作

    shell 的通配符匹配非常强大,不过也非常危险,不少同学都碰到这样的问题,比如 rm a*,结果一个手抖,a 和星号之间多了个空格,结果目录下的文件都灰飞烟灭了…… bash 支持一个特殊的变量 ! ...

  2. 我在阿里这仨月 前端开发流程 前端进阶的思考 延伸学习的方式很简单:google 一个关键词你能看到十几篇优秀的博文,再这些博文中寻找新的关键字,直到整个大知识点得到突破

    我在阿里这仨月 Alibaba 试用期是三个月,转眼三个月过去了,也到了转正述职的时间.回想这三个月做过的事情,很多很杂,但还是有重点. 本文谈一谈工作中遇到的各种场景,需要用到的一些前端知识,以及我 ...

  3. RFID-RC522 与Arduino的连接

    一.前几天在某宝上刚买了个RFID-RC522  ,目标是复制我的门禁卡(看样子没多大希望了).二.各种百度各种谷歌都没找到与Arduino的连接方式. so,分享下我的连接方式,与大家共同进步... ...

  4. 【HTML】网页中如何让DIV在网页滚动到特定位置时出现

    用js或者jquery比较好实现.但你要知道,滚动到哪个特定位置,例如滚动到一个标题h3那显示这个div,那么可以用jquery算这个h3距离网页顶部的距离:$("h3").off ...

  5. win7 32位 安装opencv-python后,运行时提示 "from .cv2 import *: DLL load failed: 找不到指定的模块" 的解决办法

    安装opencv后,运行一个测试程序提示"from .cv2 import *: DLL load failed: 找不到指定的模块".于是百度一下解决办法,结果试了N多方法后也没 ...

  6. matlab入门笔记(二):矩阵和数组

    摘自<matlab从入门到精通>胡晓东 matlab最基本的数据结构就是矩阵,一个二维的.长方形形状的数据,可以用易于使用的矩阵形式来存储,这些数据可以是数字,字符.逻辑状态,甚至是mat ...

  7. UnicodeDecodeError: 'utf-8' codec can't decode byte

    for line in open('u.item'): #read each line whenever I run this code it gives the following error: U ...

  8. Keras 2.0版本运行

    Keras 2.0版本运行demo出错: d:\program\python3\lib\site-packages\ipykernel_launcher.py:8: UserWarning: Upda ...

  9. 【转】WARNING! File system needs to be upgraded. You have version null and I want version 7. Run the '${HBASE_HOME}/bin/hbase migrate' script. 的解决办法

    前段时间集群出问题,hadoop和hbase启动不了了. 后来hadoop回复了,hbase死活master无法启动.打开日志发现报了以下错误: WARNING! File system needs ...

  10. MySQL的体系结构图

    http://attachbak.dataguru.cn/attachments/forum/201408/30/231337wrbs3xpr5kbs3ryh.png