python常用函数

函数(方法)      功能                                              
type()  
id()  
list()  
tuple()  
dict()  
str()  

 

 

 

 

 

 

 

 

1.type():接受一个对象作为参数,并返回它的类型。它的返回值是一个类型对象。

>>> type(123)      #整数
<class 'int'>
>>> type('Hello,world')    #字符串
<class 'str'>
>>> type(12.2+1j)      #复数
<class 'complex'>
>>> type(12.3)         #浮点数
<class 'float'>
>>> type([1,2,3,4])      #列表
<class 'list'>
>>> type({'name':'kebi','age':28})      #字典
<class 'dict'>
>>> type((1,2,3,4))     #元组
<class 'tuple'>
>>> type(True)         #布尔型
<class 'bool'>

 

type()作为类型函数,可以检测所有数据的类型。常见的数据类型:整数、长整数、浮点数、复数、元祖、列表、字典、字符串以及布尔型

上面的对象通过其返回值可知对象的类型,返回值又是一个类型对象。

>>> type(type(4))
<class 'type'>

2.id():可查看对象的内存地址。

>>> a = 10
>>> b = 12
>>> id(a)
1731224064
>>> id(b)
1731224128

3.list():把可迭代对象转换为列表

>>> list('wo shi ni baba')   #字符串  ————》 列表
['w', 'o', ' ', 's', 'h', 'i', ' ', 'n', 'i', ' ', 'b', 'a', 'b', 'a']
>>> list((1,2,3,4,5))        #元祖  —————》  列表
[1, 2, 3, 4, 5]

当把一个字典作为list()的参数的时候,会把键提取出来组成一个列表

>>> list({'name':'kebi','age':'28'})
['name', 'age']
>>> list({'name':'kebi','age':'28','sex':'women'})
['name', 'age', 'sex']

4.str():把obj对象转化为字符串。

>>> str(123)
'123'
>>> str([1,2,3,4])
'[1, 2, 3, 4]'
>>> str((1,2,3,4,5))
'(1, 2, 3, 4, 5)'
>>> str({'name':'kebi','age':'28'})
"{'name': 'kebi', 'age': '28'}"

5.tuple():把一个可迭代对象转换成一个元祖对象。

>>> tuple('Hello,word')       #字符串 ————》 元祖
('H', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'd')
>>> tuple([1,2,3,4])          #列表 ————》 元祖
(1, 2, 3, 4)

字符串(tuple)——》元组——》(list)列表——》(join)字符串

列表()

>>> ssg = tuple('Hello,word')
>>> ssg
('H', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'd')
>>> ''.join(list(ssg))
'Hello,word'

 

posted @ 2017-10-24 19:18  明王不动心  阅读(244)  评论(0编辑  收藏  举报