Python中一切皆是对象,主要的内置对象有:1. 数字(整型int、浮点型float)2. 字符串(不可变性) 3.列表 4.字典 5.元组(不可变性) 6.文件 7.集合(不重复性)

数字:支持+-*/运算,有强大的math模块

>>> round(3.1415926,2)
3.14(保留小数点位数)

>>> num = '%.2f' %3.1414596
>>> num
'3.14'(字符串格式化,输出为字符串)

字符串:切片、索引、查找、替换、格式化,循环

>>> 'ming'[2] 索引
'n'
>>> 'ming'.index('n') 索引
2
>>> 'ming'.find('n')查找还可以用re模块
2
>>> 'ming'.replace('n','m')替换修改字符串的一个方法
'mimg'
>>> 'I am %s and %d years old' %('ming',18)字符串的格式化
'I am ming and 18 years old'

>>> 'ming'[::-1]
'gnim' 反转功能

列表:切片、索引、循环、追加、

>>> l.append('ming') append追加至列表
>>> l
['hello', 'world', 'python', 'ming']

>>> l.extend('lily') extend是加的列表和append有区别
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y']

>>> l.extend(['hah','hey']) 追加到一个列表
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey']
>>> l.append(['nihao','hao']) 追加啥是啥
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey', ['nihao', 'hao']]

>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey', ['nihao', 'hao']]
>>> l.sort() 嵌套列表不支持排序
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
l.sort()
TypeError: '<' not supported between instances of 'list' and 'str'
>>> l
['hah', 'hello', 'hey', 'i', 'l', 'l', 'lily', 'ming', 'python', 'world', 'y', ['nihao', 'hao']]
>>> l=['l','h','i']
>>> l.sort()
>>> l
['h', 'i', 'l']
>>> l.reverse() 取反
>>> l
['l', 'i', 'h']

字典:映射、嵌套、循环、排序

>>> dict = {'ming':'hangzhou','li':'nanjing','lucy':'shanghai'}
>>> dict['li'] 映射
'nanjing'
>>> dict['jim'] = 'shenzhne' 填充字典
>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}

>>> l = list(dict.keys()) 获取字典的键
>>> l
['ming', 'li', 'lucy', 'jim']
>>> l.sort() 排序
>>> l
['jim', 'li', 'lucy', 'ming']
>>> for each in l: 格式化输出
print(each,dict[each])

jim shenzhne
li nanjing
lucy shanghai
ming hangzhou

>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}
>>> value = dict.get('good','moring')字典的查找get方法,没有则返回预设值而不报错
>>> value
'moring'
>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}
>>>