变量
什么是变量
所谓变量,指的是在程序运行过程中需要用到的中间结果,变量定义后,会占用一块内存开辟的空间地址,通过内存空间确保同一时间的唯一性。
>>> print(id.__doc__) Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.)
变量的命名规则
1)变量只能是大小写字母、数字和下划线的任意组合,并且开头不能是数字。
2)python中的关键字不能声明为变量使用。
3)变量名描述性要强
>>> 1_level = 1 File "<stdin>", line 1 1_level = 1 ^ SyntaxError: invalid syntax >>> level_1 = 1 >>> _level1 = 1 >>> print = 10 >>> print(level_1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable
字符编码
ASCII(美国标准信息交换代码)字符编码,用于显示现代英语和西欧语言,最多只能用8位来表示,即1字节,最多2**8 - 1 = 255个符号。
关于中文
1980年设计出了用于存储中文的GB2312,一共收录7445个字符,包括6763个字符和682个其他符号。
1995年设计出了可以收录21886个符号的GBK1.0,2000年GB18030取代GBK1.0的正式国家标准,可以收录27848的汉字。
为了解决不同国家之间经常出现的字符不兼容问题,推出了Unicode(统一码,万国码,单一码),为每种语言的每个字符制定了统一的并且唯一的二进制编码,每个字符统一占用2个字节。
为了解决Unicode在存储英文时多占用1个字节,继续优化出了世界上最流行的UTF8可变长字符编码,英文1个字符还占1个字节,欧洲语言1个字符占2个字节,中文1个字符占3个字节。
python2的解释器在加载.py字节码文件时,使用默认的(ASCII)字符编码,于是不支持中文。
cat hello.py #!/usr/bin/env python print '世界,你好' python hello.py File "hello.py", line 2 SyntaxError: Non-ASCII character '\xe4' in file hello.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
那么,在Python2中,使用中文时需要声明支持中文的字符编码。
cat hello.py #!/usr/bin/env python #-*- coding:utf-8 -*- print '世界,你好' python hello.py 世界,你好
python3默认会使用UTF-8字符编码,默认就支持中文。
Python 3.5.2 (default, Dec 2 2016, 17:47:43) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print('世界,你好') 世界,你好
数据类型
数字类型:不加引号的数字
int(整型)
在32位的系统上,整数的位数为32,取值范围从-2**31~2**31-1,即:-2147483648~2147483647
在64为的系统上,整数的位数为64,取值范围从-2**63~2**63-1,即:-9223372036854775808~9223372036854775807
long(长整形)
在python2中使用,如果整数发生溢出,python会自动将整数数值转换为长整形数值,python3中已经不再使用。
float(浮点型)
属于有理数中特定子集的数的数据表示,大约理解为小数,占用8个字节。
数字类型创建
>>> number = 10 >>> type(number) <class 'int'> >>> number = int(10) >>> type(number) <class 'int'>
布尔值
真或假 True False 1 或 0 ,真代表条件成立。
>>> 12 + 20 > 30 True >>> 12 + 20 > 35 False
字符串类型:被引号括起来的字符,字符串不能被修改!
字符串创建:可以使用单引号、双引号以及三个单引号或者三个双引号创建,三引号可以换行。
>>> string = 'hello world' >>> string 'hello world' >>> string = "hello world" >>> string 'hello world' >>> string = '''hello ... world''' >>> string 'hello\nworld' >>> string = """hello ... world""" >>> string 'hello\nworld'
还可以指定字符串类型创建:
>>> string = str('hello world')
>>> type(string)
<class 'str'>
>>> string
'hello world'
字符串常用方法:
strip(): 去除字符串两侧的空格,lstrip()去除字符串左侧的空格,rstrip()去除字符串右侧的空格。
>>> name = ' pangjinniu ' >>> print(name.lstrip()) pangjinniu >>> print(name.rstrip()) pangjinniu >>> print(name.strip()) pangjinniu
下标:取字符串中的1个字符
>>> name ' pangjinniu ' -> j是字符串的第6个字符,使用下标时从0开始
01234567891011
>>> print(name[5]) j
字符串不能被修改:
>>> name[1] = 'P'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
切片: 取字符串中的多个字符,切片的方法叫顾头不顾尾。
>>> string = "hello world"
012345678910
>>> string[0:5] 'hello' >>> string[6:] 'world'
切片默认从左往右,-号表示从右往左。 >>> string = '123456789' >>> string[:] '123456789' >>> string[::-1] '987654321'
通过使用步长,可以指定每次取出几个字符后显示第1个字符。 >>> string[::2] '13579' >>> string[::-2] '97531'
拼接: 使用+号,每拼接1次就会开辟一块内存空间,不推荐使用,字符串类型和数字类型不能拼接。
>>> name = 'pangjinniu' >>> age = '31' >>> print('my name is '+name+' i\'m '+age+' years old.') my name is pangjinniu i'm 31 years old. 只能是字符串之间完成拼接 >>> age = 31 >>> print('my name is '+name+' i\'m '+age+' years old.') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
格式化输出:使用%,可以传入多种数据类型。
>>> name = 'pangjinniu' >>> age = 31 >>> print('my name is %s , i\'m %s years old.' % (name,age)) my name is pangjinniu , i'm 31 years old. >>> print('my name is {0} , i\'m {1} years old.'.format(name,age)) my name is pangjinniu , i'm 31 years old. >>> print('my name is {_name} , i\'m {_age} years old.'.format(_name=name,_age=age)) my name is pangjinniu , i'm 31 years old.
split():字符串切分并返回列表类型,默认使用空格进行切分
>>> string = 'hello world' >>> print(string.split()) ['hello', 'world']
center():字符串内容居中与填充
>>> string = 'hello world' >>> len(string) 11 >>> string.center(21,"*") '*****hello world*****'
count(): 统计字符串里某个字符出现的次数
>>> string = 'hello world' 012345678910
从头到尾: >>> string.count('o') 2
从字符串位置1到7: >>> string.count('o',0,7) 1
startswith():判断字符串是否以指定前缀开头
>>> string.startswith('h') True >>> string.startswith('w') False 指定搜索范围 >>> string.startswith('w',6) True
endswith():判断字符串是否以指定后缀结尾
>>> string = 'hello world' >>> string.endswith('d') True >>> string.endswith('o') False 指定搜索的范围 >>> string.endswith('o',0,5) True
find():检查字符串中是否包含子字符串
>>> string 'hello world' 返回下标位置 >>> string.find('hello') 0 >>> string.find('o') 4 >>> string.find('world') 6 没有找到返回-1 >>> string.find('World') -1
index()与find()相似,只是在没有找到子字符串后会报错
>>> string = 'hello world' >>> string.index('hello') 0 >>> string.index('world') 6 >>> string.index('World') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
isalnum():检查字符串是否由字母或数字组成
>>> string = 'pangjinniu' >>> string.isalnum() True
>>> string = '31' >>> string.isalnum() True
>>> string = 'pangjinniu31' >>> string.isalnum() True
>>> string = 'pangjinniu ' >>> string.isalnum() False
isalpha():字符串只由数字组成
>>> string = '31'
>>> string.isdigit()
True
>>> string = 'pangjinniu31'
>>> string.isdigit()
False
join():将序列中的元素添加指定字符,并生成新的字符串
>>> string = ('','usr','local','bin') >>> '/'.join(string) '/usr/local/bin'
replace():将字符创中旧的字符串转换为新的字符串
>>> string = 'hello world' >>> string.replace('hello','Hello') 'Hello world'
列表常用方法
append():追加成员
>>> name = ['user1','user3','user4'] >>> name.append('user5') >>> name ['user1', 'user3', 'user4', 'user5']
insert():插入成员到任意位置,通过下标指定。
>>> name.insert(1,'user2') >>> name ['user1', 'user2', 'user3', 'user4', 'user5']
del:通过下标删除成员
>>> name ['user1', 'user2', 'user3', 'user4', 'user5'] >>> del name[2] >>> name ['user1', 'user2', 'user4', 'user5']
remove():直接删除列表中的成员
>>> name ['user1', 'user2', 'user4', 'user5'] >>> name.remove('user4') >>> name ['user1', 'user2', 'user5']
pop():显示列表指定位置的成员并删除,默认显示、删除最后一个成员
>>> name = ['user1','user2','user3','user4','user5'] >>> name.pop() 'user5' >>> name ['user1', 'user2', 'user3', 'user4'] >>> name.pop(0) 'user1' >>> name ['user2', 'user3', 'user4']
使用append(pop())感觉就像是队列 >>> name.append(name.pop()) >>> name ['user2', 'user3', 'user4']
index():查看列表成员的下标位置
>>> name ['user1', 'user2', 'user5'] >>> name.index('user2') 1
>>> name[name.index('user2')] = 'User2'
>>> name
['User2', 'user3', 'user4']
count():统计列表中成员出现的次数
>>> name ['user1', 'user2', 'user5', 'user2'] >>> name.count('user2') 2
sort():按照ASCII码顺序排序列表
>>> name.sort() >>> name ['user1', 'user2', 'user2', 'user5']
reverse():反向排序
>>> name.reverse() >>> name ['user5', 'user2', 'user2', 'user1']
运算:and or not in not in is is not
name = 'pangjinniu' age = 29 mac = True and >>> name == 'pangjinniu' and age < 30 True >>> name == 'pangjinniu' and age > 30 False or >>> name == 'pangjinniu' or age > 30 True >>> name == 'pangjinniu ' or age > 30 False or ... and , or 后面是一个整体条件 >>> mac = False >>> age > 30 or name == 'pangjinniu' and mac == True False >>> mac = True >>> age > 30 or name == 'pangjinniu ' and mac == True False not >>> mac = False >>> age > 30 or name == 'pangjinniu' and not mac == True True in >>> names = ['user1','user2','user3'] >>> name = 'user1' >>> name in names True not in >>> name not in names False is >>> name is 'user1' True >>> name is 'user2' False is not False >>> name is not 'user1' False >>> name is not 'user2' True