- 1、变量
- 命名风格
- input: 接收用户的输入
- 可以迭代的变量有str,list,dict,set,tuple
- Python字符串格式化
- 内置函数(常用的操作方法)
- startswith()判断字符串以某个字符串开头,返回boolean类型
- endswith()判断字符串以某个字符串结尾,返回boolean类型
- find()在字符串中查找指定字符串,找不到时返回-1:
- index()在字符串中查找指定的字符串,找不到时直接报错
- format()格式化输出字符串
- join()字符串连接 (将列表转为字符串)
- isalnum()判断字符串是否包含字母数字字符
- isalpha()判断是否只包含字母:
- isdigit()判断字符串只由数字构成:
- isspace()判断字符串是否是空格:
- isupper()判断字符串是否全是大写字符:
- lower()将所有的大写字符转为小写字符:
- lstrip()去除字符串左边的空格:
- rstrip()去除字符串右边的空格:
- strip()去除字符串2边的空格:
- replace()字符串替换:
- split()字符串分割,默认是空格:
- 2.3)列表(list)
- 结果
- 指定开始位置,不指定结束位置
- 结果
- 2.4) 元组(tuple)
- 列表转元组
- 元组转列表
- 2.5)字典(dict)
1、变量
变量是什么
变量用来标识数据语法: 变量名 = 值(数据)
变量名的命名规范
1)由数字、字母、下划线组成2)不能以数字开头3)不能是关键字,比如def,if,while等#查看关键字import keywordprint(keyword.kwlist)4)区分大小写
变量名(标识符)
命名风格
下划线命名法 比如 config_address大驼峰命名 比如 ConfigAddress小驼峰命名 比如 configAddress
2、数据类型
获取当前数据类型: type()
数据类型: 数值、字符串、布尔值
2.1)数值类型及运算
算术运算符: +、-、、/、%
赋值运算符: =,+=,-=,= , /=, %=
比较运算符: ==(等于) != (不等于) > < >= <= (结果: 布尔值,用于if语句中)
逻辑运算符: and(与),or(或),not (非)
+=a += b 相当于 a = a + b-= a -= b 相当于 a = a - b*= a *= b 相当于 a = a * b/= a /= b 相当于 a = a / b**= a **= b 相当于 a = a ** b 指数//= a //= b 相当于 a = a // b 整除
a = 5b = 20if (a <= b):print("5 - a 小于等于 b")else:print("5 - a 大于 b")if (b >= a):print("6 - b 大于等于 a")else:print("6 - b 小于 a")
input: 接收用户的输入
#字符串的额数字,转换成int类型 int()age = int(input("请输入你的年龄:"))height = int(input("请输入您择偶的身高:"))salary = int(input("请输入您择偶的收入:"))if age > 20 and height >175 and salary >= 10000:print('非常满意')elif age > 20 and height >160 and height <=175 and salary > 8000 and salary < 10000:print('满意')else:print('不满意')
2.2)字符串操作
- 单引号、双引号、三引号(单、双)
- 空字符串: s=’’
- 转换字符串: str()
Python字符串运算符
+: 字符串连接<br /> [ : ]: 通过索引获取字符串中的字符 (**左闭右开**)<br /> in and not in 成员运算符<br /> % 格式字符串<br />字符串是 Python 中最常用的数据类型。我们可以使用引号( **'** 或 **"** )来创建字符串。<br />创建字符串很简单,只要为变量分配一个值即可。例如:
var1 = 'Hello World!'var2 = "Runoob"
Python 访问字符串中的值 (查,取值)
Python 访问子字符串,可以使用方括号来截取字符串,如下实例: ```bash var1 = ‘Hello World!’ var2 = “Runoob”
print (“var1[0]: “, var1[0]) print (“var2[1:5]: “, var2[1:5])
- 从0开始,正向取值: +1,逆向取值: -1- 步长为正: 正序切 ; 步长为负: 倒序切- 左闭右开- 默认起始索引为0,步长为1```pythons10='hello world'print(s10[0:2]) #heprint(s10[0:-2]) #hello worprint(s10[-1:]) #-dprint(s10[-1:-5:-1]) # [::-1] 字符串反转
Python 字符串更新 (改)
var1 = 'Hello World!'print ("已更新字符串 : ", var1[:6] + 'Runoob!')
IN and NOT IN
a = "Hello"b = "Python"print "a + b 输出结果:", a + bprint "a * 2 输出结果:", a * 2print "a[1] 输出结果:", a[1]print "a[1:4] 输出结果:", a[1:4]if( "H" in a) :print "H 在变量 a 中"else :print "H 不在变量 a 中"if( "M" not in a) :print "M 不在变量 a 中"else :print "M 在变量 a 中"print r'\n'print R'\n'
循环(迭代及循环)
可以迭代的变量有str,list,dict,set,tuple
案例1:s10='hello world'count=0while count < len(s10):print(s10[count])count += 1#输出helloworld案例2:s10='hello world'for c in s10:print(c)
Python字符串格式化
%s: 格式化字符串
%d: 格式化整数
%f: 格式化浮点数字
print("{} {}".format('hello', 'word')) # 不设置指定位置,按默认顺序hello wordprint("{1} {0}".format('hello', 'word')) # 设置指定位置word helloprint("{1} {0} {1}".format('hello', 'word')) # 设置指定位置word hello word
print('my name is {name},my age is {age}'.format(name='jack', age=18))my name is jack,my age is 18# 通过字典设置参数dic = {'name':'jack','age':18}print('my name is {name},my age is {age}'.format(**dic))my name is jack,my age is 18# 通过列表索引设置参数my_list = ['jack', 18]print('my name is {0},my age is {1}'.format(*my_list))my name is jack,my age is 18my_list = ['jack', 18]print('my name is {0[0]},my age is {0[1]}'.format(my_list)) # "0" 是必须的my name is jack,my age is 18
案例1:
'Sam has {1:d} red balls and {0:d} yellow balls'.format(12, 31)#输出Sam has 31 red balls and 12 yellow balls
案例2: 通过列表索引设置参数
array = [34, 66, 12]"A = {0}, B = {1}, C = {2}".format(*array)#输出A = 34, B = 66, C = 12
案例3: 通过字典设置参数
d = {'hats' : 122,'mats' : 42}"Sam had {hats} hats and {mats} mats".format(**d)#输出Sam had 122 hats and 42 mats
案例4:通过字典设置参数
'Sam has {red} red balls and {green} yellow balls'.format(red = 12, green = 31)
内置函数(常用的操作方法)
startswith()判断字符串以某个字符串开头,返回boolean类型
name = "zhangsan"isTrue = name.startswith("zh")print(isTrue)# 打印结果:True
endswith()判断字符串以某个字符串结尾,返回boolean类型
name = "zhangsan"isTrue = name.endswith("san")print(isTrue)# 打印结果:True
find()在字符串中查找指定字符串,找不到时返回-1:
name = "zhangsan"isIn = name.find("an")print(isIn)# 打印结果:2# 返回字符串开始的下标
index()在字符串中查找指定的字符串,找不到时直接报错
name = "zhangsan"isIn = name.index('h')print(isIn)# 打印结果:1
format()格式化输出字符串
name = "{} {} zhangsan" #"{} {}"是占位符,用下边format()里边的参数填充name = name.format('I', 'am')print(name)# 打印结果:I am zhangsan
join()字符串连接 (将列表转为字符串)
name = "zhangsan"name = '*'.join(name)print(name)# 打印结果:z*h*a*n*g*s*a*nname=['h','e','l','l','o']newname=''.join(name)print(newname)#打印结果:hello
isalnum()判断字符串是否包含字母数字字符
name = "zhangsan1"isTrue = name.isalnum()print(isTrue)# 打印结果:Truename = "zhangsan1*"isTrue = name.isalnum()print(isTrue)# 打印结果:False
isalpha()判断是否只包含字母:
name = "zhangsan"isTrue = name.isalpha()print(isTrue)# 打印结果:Truename = "zhangsan1"isTrue = name.isalpha()print(isTrue)# 打印结果:False
isdigit()判断字符串只由数字构成:
name = "1234"isTrue = name.isdigit()print(isTrue)# 打印结果:Truename = "zhangsan1234"isTrue = name.isdigit()print(isTrue)# 打印结果:False
#错误3次就退出restr=''count=0while count < 3:num = input("请%s输入:" % restr)if num.isdigit():num = int(num)print(num)breakelif (count >= 2):print("错误次数太多")breakelse:print("请输入数字")restr = "再次"count += 1
isspace()判断字符串是否是空格:
name = " "isTrue = name.isspace()print(isTrue)# 打印结果:Truename = "zhang san"isTrue = name.isspase()print(isTrue)# 打印结果:False
isupper()判断字符串是否全是大写字符:
name = "ZHANGSAN"isTrue = name.isupper()print(isTrue)# 打印结果:True
lower()将所有的大写字符转为小写字符:
name = "ZHANGSAN"name = name.lower()print(name)# 打印结果:zhangsan
lstrip()去除字符串左边的空格:
name = " zhangsan "name = name.lstrip()print(name)# 打印结果:zhangsan
rstrip()去除字符串右边的空格:
name = " zhangsan "name = name.rstrip()print(name)# 打印结果: zhangsan
strip()去除字符串2边的空格:
name = " zhangsan "name = name.strip()print(name)# 打印结果:zhangsan
replace()字符串替换:
name = "zhangsan"name = name.replace("zhang", "li")print(name)# 打印结果:lisan
split()字符串分割,默认是空格:
name = "zhang san"name = name.split()print(name)# 打印结果:['zhang', 'san']
2.3)列表(list)
- 列表里可以存放任意类型的数据,每个数据之间,用逗号分隔,是有序的
- 整个列表被包裹在一对中括号[]里,如果你定义lst = []
- []表示一个空列表
- 与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。
索引的概念 (左闭右开)
列表是数据的有序集合,对于列表里数据的操作,都必须通过索引来完成
下面这张图很好的阐述了索引的概念lst = [2, 3, 5, 6]

所谓正序索引,就是从左向右看,倒序索引就是从右向坐看,由左至右,从0开始递增,从右向左,从-1开始递减,python既支持正序索引,也支持倒序索引
访问列表中的值
```bash list1 = [‘physics’, ‘chemistry’, 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ]
print (“list1[0]:”, list1[0]) #取值 print (“list2[1:5]: “, list2[1:5]) #切片取值
结果
list1[0]: physics list2[1:5]: [2, 3, 4, 5]
指定开始位置,不指定结束位置
lst = [3, 4, 1, 4, 2, 5, 8] lst1 = lst[2:] print(lst1)
结果
[1, 4, 2, 5, 8]
<a name="q1Jry"></a>#### 字符串和列表互为转换```bashstr="hello world hi"lst=str.split(' ')print(lst)#结果['hello', 'world', 'hi']#将列表转为字符串lst=['hello', 'world', 'hi']str=' '.join(lst)print(str)#结果hello world hi
向列表中新增数据
#append新增数据list = [] ## 空列表list.append('Google')print(list)#结果['Google']#name_list.insert(下标, 数据)list=['a',1,'c','d',2,'e']list.insert(2,'a1')print(list)#结果['a', 1, 'a1', 'c', 'd', 2, 'e']#追加数据 拆开序列追加到序列尾部list=['TOM', 'Lily', 'ROSE', 'TOM', [11, 22]]list.extend(['xiaoming', 'xiaohong'])print(list)#结果['TOM', 'Lily', 'ROSE', 'TOM', [11, 22], 'xiaoming', 'xiaohong']#修改列表的值motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)motorcycles[0] = 'ducati'print(motorcycles)#结果['honda', 'yamaha', 'suzuki']['ducati', 'yamaha', 'suzuki']
删除列表元素
#通过索引删除list=['TOM', 'Lily', 'ROSE', 'TOM', [11, 22]]del list(2)print(list)#结果['TOM', 'Lily', 'TOM', [11, 22]]#删除指定的对象list=['TOM', 'Lily', 'ROSE', 'TOM', [11, 22]]list.remove('TOM')print(list)#结果['Lily', 'ROSE', 'TOM', [11, 22]]
遍历列表**
#通过索引遍历lst = [3, 5, 8, 1, 2, 6, 9]for i in range(len(lst)):print(lst[i])#通过迭代器遍历lst = [3, 5, 8, 1, 2, 6, 9]for item in lst:print(item)
列表操作符
len: 获取列表长度
in: 数据是别表成员之一
not in: 数据不是列表成员之一
| 操作符 | 功能作用 |
|---|---|
| + | 连接两个列表 |
| * | 重复列表内容 |
| in | 成员操作符,判断某个数据是否在列表中 |
| not in | 成员操作符,判断某个数据是否在列表中 |
列表对 + 和 * 的操作符与字符串相似,现在,在交互式解释器里跟随我一起操作
>>> lst1 = [1, 2, 3]>>> lst2 = [4, 5, 6]>>> lst1 + lst2[1, 2, 3, 4, 5, 6]>>> lst1*3[1, 2, 3, 1, 2, 3, 1, 2, 3]>>> 3 in lst1True>>> 4 not in lst2False
python嵌套列表
lst = [1, [1, 5], 3, [9, 8, [1, 3]], 5]print(lst[3][2][0])print(lst[1:4])#结果1[[1, 5], 3, [9, 8, [1, 3]]]
sort() 排序:升序(默认) 和 降序
前提: 数据之间全部具有可比性,数据要统一类型**
list1 = [1, 3, 2, 5, 4, 6]list1.sort(reverse=True)print(list1)#结果[6, 5, 4, 3, 2, 1]
def cmp(x):return int(x[:-4])lst = ['1.jpg', '2.jpg', '3.jpg', '10.jpg', '20.jpg']lst.sort(key=cmp, reverse=True)print(lst)#结果['20.jpg', '10.jpg', '3.jpg', '2.jpg', '1.jpg']
2.4) 元组(tuple)
在python中,元组是一种与列表非常相似的数据类型,除了append,insert等改变数据内容的方法,列表支持的方法,元组几乎都支持, 它们之间最大的区别在于元组里的元素不能被修改
- 元组里的元素不能被修改
- 元组使用小括号,列表使用中括号
- 如果元组里只有一个元素,也必须使用逗号
- 元组与列表之间可以使用list()和tuple()函数进行转换
```bash
列表转元组
lst = [1,2,3] tup = tuple(lst) print(tup)
元组转列表
tup=(1,2,3) lst=list(tup) print(lst)
<a name="B8MUV"></a>#### 函数返回多个结果时,元组可以作为返回值```bashdef func(x, y):return x, y, x+yres = func(2, 3)print(res)#结果(2,3,5)
元组作为函数的可变参数
def func(*args):print(args, type(args))func(3, 4, 5)
访问元组
tup1 = ('physics', 'chemistry', 1997, 2000)tup2 = (1, 2, 3, 4, 5, 6, 7 )print "tup1[0]: ", tup1[0]print "tup2[1:5]: ", tup2[1:5]
元组运算符
与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组
| Python 表达式 | 结果 | 描述 |
|---|---|---|
| len((1, 2, 3)) | 3 | 计算元素个数 |
| (1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 连接 |
| (‘Hi!’,) * 4 | (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) | 复制 |
| 3 in (1, 2, 3) | True | 元素是否存在 |
| for x in (1, 2, 3): print x, | 1 2 3 |
2.5)字典(dict)
- 字典通过{}来标识
- 字典的结构{key:value}键值对来标识
- 字典是无序的,通过key获取到值
- key需要唯一,且为不可变类型

注意: 什么数据可以做key
数据必须是可hash的,下面罗列的5种数据类型是可以做字典key的数据类型
- bool
- int
- float
- 字符串
- 元组
下面3中数据类型不可以做字典的key
- 列表
- 集合
- 字典
凡是可变对象都不可以做字典的key,凡是不可变对象,都可以做字典的key
创建一个字典
字典里存储的是键值对,键值对用冒号分割key与value,每个键值(key-value)对用逗号分割,整个字典包裹在花括号{}中
contacts_dict = {"小王": '13892339876',"小张": '13898320987',"小李": '13890348745'}#空字典empty_dict = {}dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
访问字典里的值
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}print("dict['Name']: ", dict['Name'])print("dict['Age']: ", dict['Age'])#结果dict['Name']: Zaradict['Age']: 7如果用字典里没有的键访问数据,会输出错误如下:Traceback (most recent call last):File "test.py", line 5, in <module>print "dict['Alice']: ", dict['Alice'];
新增键值对和修改value
#修改value数据score_dict = {'小明': 96,'小刚': 98,'小红': 94}score_dict['小丽'] = 100print(score_dict['小丽'])#新增键值对score_dict['小兰'] = 89print(score_dict)#结果:{'小明': 96, '小刚': 98, '小红': 94, '小兰': 89}#如果key不存在Traceback (most recent call last):File "/Users/kwsy/PycharmProjects/pythonclass/mytest/demo.py", line 7, in <module>print(score_dict['小丽'])KeyError: '小丽'
删除字典
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}del dict['Name'] # 删除键是'Name'的条目dict.clear() # 清空词典所有条目del dict # 删除词典print("dict['Age']: ", dict['Age'])print("dict['School']: ", dict['School'])
python嵌套字典
stu_dict = {'name': '小明','age': 12,'score': {'语文': 90,'数学': 98}}print(stu_dict['score']['语文'])
字典遍历
#遍历键dict1 = {'name': 'TOM', 'age': 20, 'gender': '男'}for key in dict1.keys():print(key)#遍历键值对dict1 = {'name': 'TOM', 'age': 20, 'gender': '男'}for item in dict1.items():print(item)#结果('name', 'TOM')('age', 20)('gender', '男')
python字典方法介绍
| 方法 | 功能作用 |
|---|---|
| clear() | 删除字典内所有的元素 |
| copy() | 返回字典的浅复制 |
| fromkeys() | 以指定key创建一个新的字典 |
| get() | 返回指定key的值 |
| items() | 成对返回所有key和value |
| keys() | 返回字典所有的key |
| values | 返回字典所有value |
| setdefault() | 为key设置对应的默认值 |
| update() | 更新字典 |
| pop() | 删除键值对 |
#get,返回指定key的值get方法,是一种安全的获取value的方法,如果key不存在,则返回default,default可以由你来指定,如果你不指定,则默认为Noneempty_dict = {}print(empty_dict.get('python'))print(empty_dict.get('python', 100))#结果None100
