day2

一变量

声明变量

1 #!/usr/bin/env python
2 # _*_ coding:utf8 _*_
3 
4 age = 18
5 gender1 = 'male'
6 gender2 = 'female'

变量的作用:保存状态(程序的运行本质是一系列状态的变化,变量的目的就是用来保存状态,变量值的变化就是构成了程序运行的不同结果)

二数据类型

程序的本质就是驱使计算机去处理各种状态的变化,这些状态分很多种

eg:

英雄联盟游戏,一个人物角色有名字,钱,等级,装备等特性

名字:德玛西亚---------字符串

钱:10000 ------------数字

等级: 15 ---------------数字

装备:鞋子,日炎斗篷,兰顿之兆 ----------列表

python中的数据类型

python使用对象模型来存储数据,每一个数据类型都有一个类,每新建一个数据,实际就是在初始化生成一个对象,即所有数据都是对象

对象的三个特征

  • 身份:内存地址,可以用id()获取
  • 类型:决定了该对象可以保存什么类型值,可执行何种操作,需遵循什么规则,可用type()获取
  • 对象保存的真实数据

注:我们在定义数据类型,只需这样:x=1 内部生成1 这一内存对象会自动出大

标准类型 其它类型
数字 类型type
字符串 Null
列表 文件
元祖 集合
字典 函数/方法
 
  模块

标准数据类型

数字

定义:a = 1

特性:

  1. 只能存放一个值
  2. 一经定义,不可更改
  3. 直接访问

分类:整形,长整型,布尔,浮点,复数

整形

python 的整形相当于C中的long型,python中的整数可以用十进制,八进制,十六进制表示

>>> 10
10  -------------------------默认十进制
>>> oct(10)
'0o12' ---------------------八进制表示整数时,数值前面要加上一个前缀"0"
>>> hex(10)
'0xa'  ----------------------十六进制表示整数时,数字前面要加上前缀0X或0x
>>> 

python2.*

在32位机器上,整数的位数为32位,取值范围-2**31 ~2**31-1,即-2147483648~2147483647

在64位机器上,整数的位数为64位,取值范围-2**63~2**63-1 即 -9223372036854775808~~9223372036854775807

长整型

python2.*

跟C语言不同,python的长整型没有指定位宽,也就是说python没有限制整型数值的大小

但实际上由于机器内存有限,所以我们使用的长整型数值不可能无限大

在使用过程中,我们如何区分长整型和整型数值呢

通常的做法是在数字尾部加一个大些的字母L或者小写字母l以表示该整数是长整型,例如

a = 9223372036854775808L

注意,自从python2起 如果发生溢出 python会自动将整型数据转换成长整型

所以如今在长整型数据后面不加字母L也不会导致严重后果了

python3.*

长整型,整型 统一归为整型

布尔bool

true和false

1和0

浮点数float

python的浮点数就是数学中的小数,类似C语言中的double

在运算中,整数与浮点数运算的结果是浮点数

浮点数也就是个小数,之所以成为浮点数,是因为按照科学计数法表示时

一个浮点数的小数点位置是可变的,比如1.23*109和12.3*108是相等的

浮点数可以用数学写法 eg:1.23,3.14,-9.01等等 但是对于很大或者很小的浮点数

就必须用科学计数法表示,把10用e替代,1.23*109就是1.23e9或者12.3哦,0.000012可以写成1.2e-5等等

整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精明的而浮点数运算则可能会有四舍五入的误差

复数

复数由实数部分和虚数部分组成,一般形式为x+yj其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数

1 >>> 1.3 + 2.5j == 1.3 + 2.5J 
2 True
3 >>> 
数字相关的内建函数
函数名 功能 示例
int 当传入参数为小数,直接去掉小数部分 int(3.5)去掉小数部分得3
round 四舍五入取小数 round(3.5)得4
math.floor 类似int,取离原小数最近但小于原小数的数 math.floor(3.5)得3
math.ceil 与math.floor相反,取离原小数最近但大于原小数的数 math.ceil(3.5)的4
long 长整形工厂函数
float 浮点型工厂函数
complex 复数工厂函数
bool 布尔型工厂函数 传入参数为非空,非零,非none均返回True
abs 取绝对值 abs(-1)的1
coerce 接受2个参数,把数据转成相同类型,返回一个元祖

coerce(-1,3.2)得(-1.0, 3.2)python2

divmod 返回元祖,包含商和余数 divmod(93,10)的(9,3)
pow 取平方 pow(2,3,3)相当于2**3%3得2,pow(2,3)等同于2**3
hex 十进制转16进制 hex(10)得'0xa'以0x开头代表16进制
oct 十进制转8进制 oct(10)的'0o12'以0开头代表8进制
ord 根据acsill表,将字符转成十进制数 ord('a')得97
chr 根据acsill表,将十进制转成字符 chr(97)得'a'

字符串

定义:它是一个有序的字符的合集,用于存储和表示基本的文本信息,''或" "或' ' 或"   "中间包含的内容称之为字符串

特性:

  1. 只能存放一个值
  2. 不可变
  3. 按照从左到右的顺序定义字符集合,小标从0开始顺序访问,有序

补充:

  1. 字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符取消特殊意义,在引号前面加r,如name=r'l hr'
  2. unicode字符串与r连用必需在r前面,如name=ur'l hf'

字符工厂函数str

#!/usr/bin/env python
# _*_conding:utf-8 _*_

#首字母大写capitalize()
>>> name = 'hello world'
>>> name.capitalize()
'Hello world'
>>> 

#原来字符居中,不够用空格补全center()
>>> name.center(30)
'         hello world          '
>>> name.center(30,"#")
'#########hello world##########'
>>> 

#从一个范围内的统计某str出现的次数count()   
>>> name = 'hello world'
>>> name.count('l')     
3
>>> name.count('l',4,-1)
1
>>> name.count('l',0,4) 
2

#以encoding指定编码格式编码,如果出错默认报一个ValueError,除非error指定的ignore或replace


#判断是否以'x'字符串结尾 返回布尔值endswith()
>>> name = 'hello world'
>>> name.endswith('w')
False
>>> name.endswith('d')
True

#将字符串中包含	转换成tabsize个空格expandtabs()
>>> name = 'hello	world'
>>> name.expandtabs(20)
'hello               world'
#查找字符串的位置find()
S.find(sub[, start[, end]]) -> int
>>> name = 'hello world'
>>> name.find('world')  
6
>>> name.find('world',3,11)
6

#字符串格式化format()
#1通过位置
>>> '{0},{1}'.format('kzc',18)
'kzc,18'
>>> 
#2关键字参数
>>> '{name},{age}'.format(age=18,name='kzc')  
'kzc,18'
>>> 
#3.下标
>>> '{0[0]},{0[1]}'.format(p) 
'kzc,18'
>>> 
#4.填充与对齐
>>> '{:>8}'.format('189')
'     189'
>>> '{:0>8}'.format('189')
'00000189'
>>> '{:a>8}'.format('189')
'aaaaa189'
#5.精度与类型f
>>> '{:.2f}'.format(321.33345)
'321.33'
>>> 
#6.其他类型进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。
>>> '{:b}'.format(17)
'10001'
>>> '{:d}'.format(17)
'17'
>>> '{:o}'.format(17)
'21'
>>> '{:x}'.format(17)
'11'

#字符串格式化,从字典输入(format_map)
>> maping_name = {'name':['morgana','hello'],'age':[18,19]}
>>> for x in range(2):
...     print('my name is {},and i is {} old'.format(maping_name['name'][x],maping_name['age'][x]))
... 
my name is morgana,and i is 18 old
my name is hello,and i is 19 old

#字符串的索引位置
>>> title='TODAY	is	a	GOOD	day'
>>> title_ca=title.index('Y')
>>> print(title_ca)
4

#至少一个字符,且都是字母或数字才返回True
>>> title='18TODAY'           
>>> title_ca = title.isalnum()
>>> print(title_ca)
True

#至少一个字符,且都是字母才返回True
>>> title = '22TODAY'
>>> title_ca = title.isalpha()
>>> print(title_ca)
False
>>> title = 'TODAY'           
>>> title_ca = title.isalpha()
>>> print(title_ca)           
True
>>> a = '22TODAY'
>>> print(a.isalpha())
False

#判断字符串是否为有效标识符(可做为函数名称)字符串为关键字返回True
>>> str='hello world' 
>>> print(str.isidentifier())
False
>>> str='abc'
>>> print(str.isidentifier())
True

#判断字符串是否全小写
>>> str='HELLO WORLD'
>>> print(str.islower())
False
>>> str='hello world'
>>> print(str.islower())
True

#判断所有字符是否可打印
>>> str = ''
>>> print(str.isprintable())
True
>>> str='	
'
>>> print(str.isprintable())
False

#至少一个字符,且都是空格才返回True
>>> print(str.isspace())
True
>>> str='    '          
>>> print(str.isspace())
True
>>> str='	
'
>>> print(str.isspace())
True
>>> str='a '            
>>> print(str.isspace())
False

#istitle(self)判断字符串是否为标题格式(首字母大写)
>>> str='Hello world'   
>>> print(str.istitle())
False
>>> str='Hello World'   
>>> print(str.istitle())
True

#判断字符串是否全大写
>>> print(str.isupper())
False
>>> str='Hello World'   
>>> print(str.isupper())
False
>>> str='hello World'    
>>> print(str.isupper())
False
>>> str='HELLO WORLD'
>>> print(str.isupper())
True

#字符串连接对序列进行操作(分别使用' '与':'作为分隔符)

>>> seq1 = ('h','e','l','l','o')
>>> print (s1.join( seq1 ))
hello
>>> print(''.join(seq1))
hello
>>> print('-'.join(seq1))
h-e-l-l-o
>>> print('#'.join(seq1))
h#e#l#l#o
#对序列进行操作(分别使用' '与':'作为分隔符)
>>> seq2=['h','e','l','l','o']
>>> print('#'.join(seq2))     
h#e#l#l#o
#对元组进行操作
>>> seq3=('hello','world')
>>> print (':'.join(seq3))
hello:world
##对字典进行操作
>>> seq4={'hello':1,'good':2,'boy':3}
>>> print(':'.join(seq4))            
good:hello:boy

#合并目录
good:hello:boy
>>> import os
>>> os.path.join('/hello/','/world/')
'/world/'


#左对齐,达不到指定长度,右则填充
str='today is a good day'
>>> print(str.ljust(22,'*'))
today is a good day***

#转小写
>>> str = 'Hello World'
>>> print(str.lower())
hello world

#左边去除指定字符,默认为空格
>>> str = 'xxx today is good day'
>>> print(str.lstrip('x'))       
 today is good day

#maketrans用于创建字符映射的转换表,两个参数为长度相等的字符串
 >>> a=str.maketrans('abcdefg','hijklmn')
>>> a
{97: 104, 98: 105, 99: 106, 100: 107, 101: 108, 102: 109, 103: 110}

#partition  以sep为分割,将S分成head,sep,tail三部分
>>> str = 'today is good day'
>>> print(str.partition('a'))
('tod', 'a', 'y is good day')
>>> print(str.partition('o'))
('t', 'o', 'day is good day')
>>> print(str.partition('day'))
('to', 'day', ' is good day')

#replace:字符串替换

>>> str = 'today is a good day'
>>> str = 'today is a good day'  
>>> print(str.replace('o','x',2))
txday is a gxod day
>>> print(str.replace('o','x',3))
txday is a gxxd day

#rfind:返回查询到的字符串的最大索引
>>> str = 'today is a good day'
>>> print(str.rfind('y'))
18
>>> print(str.rfind('x'))
-1

#rindex:类似rfind,但如果没找到会报错
>>> print(str.rindex('x'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

#rjust:右对齐,左侧填充字符
>>> print(str.rjust(20,'#'))
#today is a good day
>>> print(str.rjust(100,'#'))
#################################################################################today is a good day
>>> 

#rpartition:类似partition,如果未找到字符串,则空值在左边
>>> str = 'today is a good day'
>>> print(str.rpartition('o'))
('today is a go', 'o', 'd day')
>>> print(str.rpartition('y'))
('today is a good da', 'y', '')
>>> print(str.rpartition('x'))
('', '', 'today is a good day')

#rsplit:分割字符串,从右边开始
>>> str='today is a good day'
>>> 
>>> print(str.rsplit())
['today', 'is', 'a', 'good', 'day']

#rstrip:右边去关键字符
>>> str = 'today is a good dayxxx'
>>> print(str.rstrip('xxx'))      
today is a good day

#splitlines 以sep为分割,将S切分成列表,与partition的区别在于切分结果不包含sep,如果一个字符串中包含多个sep那么maxsplit为最多切分成几部分
>>> str = 'today
is
a
good
day'  
>>> print(str.splitlines())        
['today', 'is', 'a', 'good', 'day']
>>> print(str.splitlines(1))       
['today
', 'is
', 'a
', 'good
', 'day']
>>> print(str.splitlines(0))
['today', 'is', 'a', 'good', 'day']

#startswith:如果字符串以指定的字符为前缀,则返回true,否则返回false
>>> str='today is a good day'   
>>> print(str.startswith('today'))
True
>>> print(str.startswith('day'))  
False
>>> print(str.startswith('Today'))
False

#strip:去除字符串前后的指定字
>>> str='xxxxtoday is a good dayxxx'
>>> print(str.strip('x'))           
today is a good day

#swapcase:大小写互转
>>> str ='today is a good day'
>>> print(str.swapcase())
TODAY IS A GOOD DAY
>>> str ='TODAY IS A GOOD DAY'
>>> print(str.swapcase())     
today is a good day

#title:返回的字符串为title格式,首字母大写
>>> str='today is a good day'
>>> print(str.title())       
Today Is A Good Day

#translate:根据参数table给出的表转换字符中的字符
>>> str='today is a good day'
>>> trantab={97:49}       
>>> print(str.translate(trantab))
tod1y is 1 good d1y
>>> 

#ord与chr是配对函数
>>> chr(65)
'A'
>>> ord('A')
65

#upper:将字符串转为大写
>>> str='today is a good day'    
>>> print(str.upper())
TODAY IS A GOOD DAY

#zfill:数字填零
>>> str='123'          
>>> print(str.zfill(5))
00123
isdigit()   isdecimal()  isnumeric()

>>> num = '1' #unicode
>>> num.isdigit()
True
>>> num.isdecimal()
True
>>> num.isnumeric()
True

>>> num = '' # 全角
>>> num.isdigit()
True
>>> num.isnumeric()
True
>>> num.isdecimal()
True


>>> num = b'3' #byte
>>> num.isdigit()
True
>>> num.isnumeric()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'isnumeric'
>>> num.isdecimal()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'isdecimal'

>>> num = '' #罗马数字
>>> num.isnumeric()
True
>>> num.isdecimal()
False
>>> num.isdigit()
False


>>> num = '' # 汉字
>>> num.isnumeric()
True
>>> num.isdecimal()
False
>>> num.isdigit()
False
isdigit()

True:unicode数字,全角, byte数字(单字节)

False:罗马数字,汉字

Error:无

isdecimal()

True:unicode 数字 ,全角,

False:罗马数字,汉字

Error:# byte数字(单字节)

isnumeric()

True:unicode数字,全角

False:byte数字(单字节)

Error:byte数字(单字节)
>>> import unicodedata    
>>> unicodedata.digit("5")
5
>>> unicodedata.decimal("5")
5
>>> unicodedata.numeric("5")
5.0

>>> unicodedata.digit("")
6
>>> unicodedata.decimai("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'unicodedata' has no attribute 'decimai'
>>> unicodedata.numeric("")
6.0
>>> 

>>> unicodedata.digit(b"7")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: digit() argument 1 must be a unicode character, not bytes
>>> unicodedata.decimal(b"7")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: decimal() argument 1 must be a unicode character, not bytes
>>> unicodedata.numeric(b"7")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: numeric() argument 1 must be a unicode character, not bytes
>>> 

>>> unicodedata.digit("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not a digit
>>> unicodedata.decimal("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not a decimal
>>> unicodedata.numeric("")
8.0

>>> unicodedata.digit("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not a digit
>>> unicodedata.numeric("")
4.0
>>> unicodedata.decimal("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not a decimal
>>> 

#"〇","零","一","壱","二","弐","三","参","四","五","六","七","八","九","十","廿","卅","卌","百","千","万","万","亿"

列表,元祖

列表是我们最常用的数据类型之一,通过列表可以对数据实现最方便的存储,修改等操作

定义列表

>>> names = ['morgana','katherine','gs']
>>> names[0]
'morgana'
>>> names[1]
'katherine'
>>> names[2]
'gs'
>>> names[-1]
'gs'
>>> names[-2]
'katherine'
>>> names[-3]
'morgana'

切片:取多个元素

>>> names = [ 'morgana','katherine','gs','pythoner','hanmeimei','lilei','liminhao']
>>> names[1:4]   #取下标1至下标4之间的数字,包括1,不包括4
['katherine', 'gs', 'pythoner']
>>> names[1:-1] #取下标1至-1的值,不包括-1
['katherine', 'gs', 'pythoner', 'hanmeimei', 'lilei']
>>> names[0:3] 
['morgana', 'katherine', 'gs']
>>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
['morgana', 'katherine', 'gs']
>>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
['pythoner', 'hanmeimei', 'lilei', 'liminhao']
>>> names[3:-1]#这样-1就不会被包含了
['pythoner', 'hanmeimei', 'lilei']
>>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
['morgana', 'gs', 'hanmeimei', 'liminhao']
>>> names[::2] #和上句效果一样
['morgana', 'gs', 'hanmeimei', 'liminhao']
>>> 

追加

>>> names
['morgana', 'katherine', 'gs', 'pythoner', 'hanmeimei', 'lilei', 'liminhao']
>>> names.append("new")
>>> names
['morgana', 'katherine', 'gs', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']

插入

>>> names = [ 'morgana','katherine','gs','pythoner','hanmeimei','lilei','liminhao']
>>> names
['morgana', 'katherine', 'gs', 'pythoner', 'hanmeimei', 'lilei', 'liminhao']
>>> names.append("new")
>>> names
['morgana', 'katherine', 'gs', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']
>>> names
['morgana', 'katherine', 'gs', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']
>>> names.insert(2,"强行从gs前面插入")
>>> names
['morgana', 'katherine', '强行从gs前面插入', 'gs', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']
>>> names.insert(4,"从gs后面插入")
>>> names
['morgana', 'katherine', '强行从gs前面插入', 'gs', '从gs后面插入', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']
>>>   

修改

>>> names  
['morgana', 'katherine', '强行从gs前面插入', 'gs', '从gs后面插入', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']
>>> names[2] = 'maque'
>>> names
['morgana', 'katherine', 'maque', 'gs', '从gs后面插入', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']

删除

>>> names       
['morgana', 'katherine', 'maque', 'gs', '从gs后面插入', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']
>>> del names[2]
>>> names       
['morgana', 'katherine', 'gs', '从gs后面插入', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', 'new']

>>> names = [ 'morgana','katherine','gs','pythoner','hanmeimei','lilei','liminhao']
>>> names.remove("gs")  ##删除指定元素
>>> names
['morgana', 'katherine', 'pythoner', 'hanmeimei', 'lilei', 'liminhao']
>>> 

>>> names
['morgana', 'katherine', 'pythoner', 'hanmeimei', 'lilei', 'liminhao']
>>> names.pop() #删除列表最后一个值
'liminhao'
>>> names
['morgana', 'katherine', 'pythoner', 'hanmeimei', 'lilei']
>>> 

扩展

>>> names
['morgana', 'katherine', 'pythoner', 'hanmeimei', 'lilei']
>>> b=[1,2,3]
>>> names.extend(b)
>>> names
['morgana', 'katherine', 'pythoner', 'hanmeimei', 'lilei', 1, 2, 3]
>>> 

拷贝

>>> names
['morgana', 'katherine', 'pythoner', 'hanmeimei', 'lilei', 1, 2, 3]
>>> name = names.copy()
>>> name
['morgana', 'katherine', 'pythoner', 'hanmeimei', 'lilei', 1, 2, 3]
>>> 

统计

>>> names = [ 'morgana','katherine','gs','pythoner','hanmeimei','lilei','liminhao']
>>> names.count("gs")
1
>>> 

排序&反转

>>> names
['morgana', 'katherine', 'gs', 'pythoner', 'hanmeimei', 'lilei', 'liminhao', '1', '3', '2']
>>> names.sort()
>>> names
['1', '2', '3', 'gs', 'hanmeimei', 'katherine', 'lilei', 'liminhao', 'morgana', 'pythoner']


>>> names.reverse() 
>>> names
['pythoner', 'morgana', 'liminhao', 'lilei', 'katherine', 'hanmeimei', 'gs', '3', '2', '1']
>>> 

获取下标

>>> names
['pythoner', 'morgana', 'liminhao', 'lilei', 'katherine', 'hanmeimei', 'gs', '3', '2', '1']
>>> names.index('morgana')
1
>>> 

元组

原文地址:https://www.cnblogs.com/morgana/p/5971246.html