時間:2019年12月27日
內(nèi)容:for循環(huán)荠列,字符串,列表和元祖
for循環(huán)
字符串
簡介
- 一對引號字符串
name1 = 'Tom'
name2 = "Rose"
三對引號字符串
name3 = ''' Tom '''
name4 = """ Rose """
a = ''' i am Tom,
nice to meet you! '''
b = """ i am Rose,
nice to meet you! """
注意:三引號形式的字符串支持換行谐区。
注意:控制臺顯示結(jié)果為
<class 'str'>
茂翔, 即數(shù)據(jù)類型為str(字符串)涵但。
- 思考:如果創(chuàng)建一個字符串
I'm Tom
?-
雙引號 或者
\'
-
雙引號 或者
c = "I'm Tom"
d = 'I\'m Tom'
字符串輸出
print('hello world')
name = 'Tom'
print('我的名字是%s' % name)
print(f'我的名字是{name}')
字符串輸入
-
input()
接收用戶輸入
name = input('請輸入您的名字:')
print(f'您輸入的名字是{name}')
print(type(name))
password = input('請輸入您的密碼:')
print(f'您輸入的密碼是{password}')
print(type(password))
輸出結(jié)果
下標(biāo)
“下標(biāo)”
又叫“索引”
凳兵,就是編號百新。從0開始
切片
切片是指對操作的對象截取其中一部分的操作。字符串庐扫、列表饭望、元組都支持切片操作。
- 語法
序列[開始位置下標(biāo):結(jié)束位置下標(biāo):步長]
- 不包含結(jié)束位置下標(biāo)對應(yīng)的數(shù)據(jù)形庭, 正負(fù)整數(shù)均可铅辞;
- 步長是選取間隔,正負(fù)整數(shù)均可萨醒,默認(rèn)步長為1巷挥。
- 演練
name = "abcdefg"
print(name[2:5:1]) # cde
print(name[2:5]) # cde
print(name[:5]) # abcde
print(name[1:]) # bcdefg
print(name[:]) # abcdefg
print(name[::2]) # aceg
print(name[:-1]) # abcdef, 負(fù)1表示倒數(shù)第一個數(shù)據(jù)
print(name[-4:-1]) # def
print(name[::-1]) # gfedcba
如果選取方向(下標(biāo)開始到結(jié)束的方向)和 步長的方向沖突,則無法選取數(shù)據(jù)
常用操作方法
查找
子串的位置或出現(xiàn)的次數(shù)
- find(): 返回位置下標(biāo)验靡,沒有則 返回-1
語法
字符串序列.find(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
注意:開始和結(jié)束位置下標(biāo)可以省略,表示在整個字符串序列中查找雏节。
- index(): 返回位置下標(biāo)胜嗓,沒有則 報錯
語法
字符串序列.index(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
注意:開始和結(jié)束位置下標(biāo)可以省略,表示在整個字符串序列中查找钩乍。
演練
mystr = "hello world and itcast and itheima and Python"
print(mystr.index('and')) # 12
print(mystr.index('and', 15, 30)) # 23
print(mystr.index('ands')) # 報錯
rfind(): 和find()功能相同辞州,但查找方向為==右側(cè)==開始。
rindex():和index()功能相同寥粹,但查找方向為==右側(cè)==開始变过。
- count():返回某個子串在字符串中出現(xiàn)的次數(shù)
語法
字符串序列.count(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
注意:開始和結(jié)束位置下標(biāo)可以省略,表示在整個字符串序列中查找涝涤。
演練
mystr = "hello world and itcast and itheima and Python"
print(mystr.count('and')) # 3
print(mystr.count('ands')) # 0
print(mystr.count('and', 0, 20)) # 1
修改
**replace(): 替換
語法:
字符串序列.replace(舊子串, 新子串, 替換次數(shù))
注意:不寫替換次數(shù)媚狰,則全部替換棍丐。
演練:
mystr = "hello world and itcast and itheima and Python"
# 結(jié)果:hello world he itcast he itheima he Python
print(mystr.replace('and', 'he'))
# 結(jié)果:hello world he itcast he itheima he Python
print(mystr.replace('and', 'he', 10))
# 結(jié)果:hello world and itcast and itheima and Python
print(mystr)
注意:數(shù)據(jù)按照是否能直接修改分為==可變類型==和==不可變類型==兩種甚纲。字符串類型的數(shù)據(jù)修改的時候不能改變原有字符串,屬于不能直接修改數(shù)據(jù)的類型即是不可變類型棕所。
- split(): 分割字符串
語法:
字符串序列.split(分割字符, num)
注意:num表示的是分割字符出現(xiàn)的次數(shù),即將來返回數(shù)據(jù)個數(shù)為num+1個辨宠。
演練:
mystr = "hello world and itcast and itheima and Python"
# 結(jié)果:['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr.split('and'))
# 結(jié)果:['hello world ', ' itcast ', ' itheima and Python']
print(mystr.split('and', 2))
# 結(jié)果:['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
print(mystr.split(' '))
# 結(jié)果:['hello', 'world', 'and itcast and itheima and Python']
print(mystr.split(' ', 2))
注意:如果分割字符是原有字符串中的子串遗锣,分割后則丟失該子串。
- join(): 將多個字符串合并為一個字符串
語法:
字符或子串.join(多字符串組成的序列)
演練:
list1 = ['chuan', 'zhi', 'bo', 'ke']
t1 = ('aa', 'b', 'cc', 'ddd')
# 結(jié)果:chuan_zhi_bo_ke
print('_'.join(list1))
# 結(jié)果:aa...b...cc...ddd
print('...'.join(t1))
- capitalize(): 第一個字符轉(zhuǎn)換成大寫嗤形。
mystr = "hello world and itcast and itheima and Python"
# 結(jié)果:Hello world and itcast and itheima and python
print(mystr.capitalize())
注意:capitalize()函數(shù)轉(zhuǎn)換后精偿,只字符串第一個字符大寫,其他的字符全都小寫赋兵。
- title(): 每個單詞首字母轉(zhuǎn)換成大寫笔咽。
mystr = "hello world and itcast and itheima and Python"
# 結(jié)果:Hello World And Itcast And Itheima And Python
print(mystr.title())
- upper(): 小寫轉(zhuǎn)大寫。
mystr = "hello world and itcast and itheima and Python"
# 結(jié)果:HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON
print(mystr.upper())
- lower(): 大寫轉(zhuǎn)小寫
mystr = "hello world and itcast and itheima and Python"
# 結(jié)果:hello world and itcast and itheima and python
print(mystr.lower())
-
lstrip(): 刪除左側(cè)空白字符
image-20190129213453010.png -
rstrip(): 刪除右側(cè)空白字符
image-20190129213558850.png -
strip(): 刪除兩側(cè)空白字符
image-20190129213637584.png ljust(): 返回新字符串
字符串序列.ljust(長度, 填充字符)
- rjust():返回一個原字符串右對齊,并使用指定字符(默認(rèn)空格)填充至對應(yīng)長度 的新字符串毡惜,語法和ljust()相同拓轻。
-
center():返回一個原字符串居中對齊,并使用指定字符(默認(rèn)空格)填充至對應(yīng)長度 的新字符串,語法和ljust()相同经伙。
image-20190130141442074.png
判斷
- startswith(): 檢查是否以指定子串開頭扶叉。
語法:
字符串序列.startswith(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
演練:
mystr = "hello world and itcast and itheima and Python "
# 結(jié)果:True
print(mystr.startswith('hello'))
# 結(jié)果False
print(mystr.startswith('hello', 5, 20))
-endswith(): 是否以某個子串結(jié)尾
語法:
字符串序列.endswith(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
演練:
mystr = "hello world and itcast and itheima and Python"
# 結(jié)果:True
print(mystr.endswith('Python'))
# 結(jié)果:False
print(mystr.endswith('python'))
# 結(jié)果:False
print(mystr.endswith('Python', 2, 20))
- isalpha(): 都是字母True,否則False帕膜。
mystr1 = 'hello'
mystr2 = 'hello12345'
# 結(jié)果:True
print(mystr1.isalpha())
# 結(jié)果:False
print(mystr2.isalpha())
- isdigit(): 都是數(shù)字True枣氧,否則False。
mystr1 = 'aaa12345'
mystr2 = '12345'
# 結(jié)果: False
print(mystr1.isdigit())
# 結(jié)果:False
print(mystr2.isdigit())
- isalnum(): 至少有一個字符且全部是字母或數(shù)字返 回 True,否則False垮刹。
mystr1 = 'aaa12345'
mystr2 = '12345-'
# 結(jié)果:True
print(mystr1.isalnum())
# 結(jié)果:False
print(mystr2.isalnum())
- isspace(): 全部空白返回True达吞,否則False。
mystr1 = '1 2 3 4 5'
mystr2 = ' '
# 結(jié)果:False
print(mystr1.isspace())
# 結(jié)果:True
print(mystr2.isspace())
列表
作用:一次性存儲多個數(shù)據(jù)
格式:
[數(shù)據(jù)1, 數(shù)據(jù)2, 數(shù)據(jù)3, 數(shù)據(jù)4, ......]
列表可以一次性存儲多個數(shù)據(jù)荒典,且可以為不同數(shù)據(jù)類型酪劫。
查找
下標(biāo)
name_list = ['Tom', 'Lily', 'Rose']
print(name_list[0]) # Tom
print(name_list[1]) # Lily
print(name_list[2]) # Rose
函數(shù)
index(): 返回位置
語法:
列表序列.index(數(shù)據(jù), 開始位置下標(biāo), 結(jié)束位置下標(biāo))
name_list = ['Tom', 'Lily', 'Rose']
print(name_list.index('Lily', 0, 2)) # 1
注意:如果查找的數(shù)據(jù)不存在則報錯。
count(): 出現(xiàn)的次數(shù)
name_list = ['Tom', 'Lily', 'Rose']
print(name_list.count('Lily')) # 1
len(): 列表長度=數(shù)據(jù)個數(shù)寺董。
name_list = ['Tom', 'Lily', 'Rose']
print(len(name_list)) # 3
判斷是否存在
in: 判斷數(shù)據(jù)在列表覆糟,在返回True,否則返回False
name_list = ['Tom', 'Lily', 'Rose']
# 結(jié)果:True
print('Lily' in name_list)
# 結(jié)果:False
print('Lilys' in name_list)
not in:判斷指定數(shù)據(jù)不在某個列表序列遮咖,如果不在返回True滩字,否則返回False
name_list = ['Tom', 'Lily', 'Rose']
# 結(jié)果:False
print('Lily' not in name_list)
# 結(jié)果:True
print('Lilys' not in name_list)
體驗案例:
需求:查找用戶輸入的名字是否已經(jīng)存在。
name_list = ['Tom', 'Lily', 'Rose']
name = input('請輸入您要搜索的名字:')
if name in name_list:
print(f'您輸入的名字是{name}, 名字已經(jīng)存在')
else:
print(f'您輸入的名字是{name}, 名字不存在')
列表增加數(shù)據(jù)
作用:增加指定數(shù)據(jù)到列表中御吞。
append(): 列表結(jié)尾追加數(shù)據(jù)麦箍。
語法:
列表序列.append(數(shù)據(jù))
name_list = ['Tom', 'Lily', 'Rose']
name_list.append('xiaoming')
# 結(jié)果:['Tom', 'Lily', 'Rose', 'xiaoming']
print(name_list)
列表追加數(shù)據(jù)的時候,直接在原列表里面追加了指定數(shù)據(jù)陶珠,即修改了原列表挟裂,故列表為可變類型數(shù)據(jù)。
注意點:
如果append()追加的數(shù)據(jù)是一個序列背率,則追加整個序列到列表
name_list = ['Tom', 'Lily', 'Rose']
name_list.append(['xiaoming', 'xiaohong'])
# 結(jié)果:['Tom', 'Lily', 'Rose', ['xiaoming', 'xiaohong']]
print(name_list)
extend(): 列表結(jié)尾追加數(shù)據(jù)话瞧,如果數(shù)據(jù)是一個序列嫩与,則將這個序列的數(shù)據(jù)逐一添加到列表。
語法:
列表序列.extend(數(shù)據(jù))
name_list = ['Tom', 'Lily', 'Rose']
name_list.extend('xiaoming')
# 結(jié)果:['Tom', 'Lily', 'Rose', 'x', 'i', 'a', 'o', 'm', 'i', 'n', 'g']
print(name_list)
name_list = ['Tom', 'Lily', 'Rose']
name_list.extend(['xiaoming', 'xiaohong'])
# 結(jié)果:['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaohong']
print(name_list)
insert(): 指定位置新增數(shù)據(jù)交排。
語法:
列表序列.insert(位置下標(biāo), 數(shù)據(jù))
name_list = ['Tom', 'Lily', 'Rose']
name_list.insert(1, 'xiaoming')
# 結(jié)果:['Tom', 'xiaoming', 'Lily', 'Rose']
print(name_list)
列表刪除數(shù)據(jù)
del
語法:
del 目標(biāo)
刪除列表
name_list = ['Tom', 'Lily', 'Rose']
# 結(jié)果:報錯提示:name 'name_list' is not defined
del name_list
print(name_list)
刪除指定數(shù)據(jù)
name_list = ['Tom', 'Lily', 'Rose']
del name_list[0]
# 結(jié)果:['Lily', 'Rose']
print(name_list)
op():刪除指定下標(biāo)的數(shù)據(jù)(默認(rèn)為最后一個)划滋,并返回該數(shù)據(jù)。
語法:
列表序列.pop(下標(biāo))
name_list = ['Tom', 'Lily', 'Rose']
del_name = name_list.pop(1)
# 結(jié)果:Lily
print(del_name)
# 結(jié)果:['Tom', 'Rose']
print(name_list)
remove():移除列表中某個數(shù)據(jù)的第一個匹配項埃篓。
語法:
列表序列.remove(數(shù)據(jù))
name_list = ['Tom', 'Lily', 'Rose']
name_list.remove('Rose')
# 結(jié)果:['Tom', 'Lily']
print(name_list)
clear():清空列表
name_list = ['Tom', 'Lily', 'Rose']
name_list.clear()
print(name_list) # 結(jié)果: []
列表數(shù)據(jù)修改
- 修改制定下標(biāo)數(shù)據(jù)
name_list = ['Tom', 'Lily', 'Rose']
name_list[0] = 'aaa'
# 結(jié)果:['aaa', 'Lily', 'Rose']
print(name_list)
- 逆置:reverse()
num_list = [1, 5, 2, 3, 6, 8]
num_list.reverse()
# 結(jié)果:[8, 6, 3, 2, 5, 1]
print(num_list)
- 排序:sort()
語法:
列表序列.sort( key=None, reverse=False)
num_list = [1, 5, 2, 3, 6, 8]
num_list.sort()
# 結(jié)果:[1, 2, 3, 5, 6, 8]
print(num_list)
num_list.sort(reverse=True)
# 結(jié)果:[8, 6, 5, 3, 2, 1]
print(num_list)
列表復(fù)制數(shù)據(jù)
函數(shù):copy()
name_list = ['Tom', 'Lily', 'Rose']
name_li2 = name_list.copy()
# 結(jié)果:['Tom', 'Lily', 'Rose']
print(name_li2)
列表的遍歷之while
name_list = ['Tom', 'Lily', 'Rose']
i = 0
while i < len(name_list):
print(name_list[i])
i += 1
列表遍歷之for
name_list = ['Tom', 'Lily', 'Rose']
for i in name_list:
print(i)
列表嵌套
列表嵌套指的就是一個列表里面包含了其他的子列表处坪。
應(yīng)用場景:要存儲班級一、二架专、三三個班級學(xué)生姓名同窘,且每個班級的學(xué)生姓名在一個列表。
name_list = [['小明', '小紅', '小綠'], ['Tom', 'Lily', 'Rose'], ['張三', '李四', '王五']]
思考: 如何查找到數(shù)據(jù)"李四"部脚?
# 第一步:按下標(biāo)查找到李四所在的列表
print(name_list[2])
# 第二步:從李四所在的列表里面想邦,再按下標(biāo)找到數(shù)據(jù)李四
print(name_list[2][1])
綜合應(yīng)用
需求:有三個辦公室,8位老師委刘,8位老師隨機分配到3個辦公室
# 1. 準(zhǔn)備數(shù)據(jù)
teachers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
offices = [[], [], []]
# 2. 分配老師到辦公室 -- 取到每個老師放到辦公室列表 -- 遍歷老師列表數(shù)據(jù)
for name in teachers:
# 列表追加數(shù)據(jù) -- append(選中) extend insert
# xx[0] -- 不能指定是具體某個下標(biāo) -- 隨機
num = random.randint(0,2)
offices[num].append(name)
# print(num)
# print(offices)
# 為了更貼合生活丧没,把各個辦公室子列表加一個辦公室編號1,2锡移,3
i = 1
# 3. 驗證是否分配成功
for office in offices:
# 打印辦公室人數(shù) -- 子列表數(shù)據(jù)的個數(shù) len()
print(f'辦公室{i}的人數(shù)是{len(office)}呕童,老師分別是:')
# 打印老師的名字
# print() -- 每個子列表里面的名字個數(shù)不一定 -- 遍歷 -- 子列表
for name in office:
print(name)
i += 1
列表總結(jié)
- 列表的格式
[數(shù)據(jù)1, 數(shù)據(jù)2, 數(shù)據(jù)3]
-
常用操作方法
- index()
- len()
- append()
- pop()
- remove()
列表嵌套
name_list = [['小明', '小紅', '小綠'], ['Tom', 'Lily', 'Rose'], ['張三', '李四', '王五']]
name_list[2][1]
元祖
元祖簡介
一個元組可以存儲多個數(shù)據(jù),元組內(nèi)的數(shù)據(jù)是不能修改的淆珊。
元組特點:定義元組使用 小括號
夺饲,且逗號
隔開各個數(shù)據(jù),數(shù)據(jù)可以是不同的數(shù)據(jù)類型施符。
# 多個數(shù)據(jù)元組
t1 = (10, 20, 30)
# 單個數(shù)據(jù)元組
t2 = (10,)
注意:如果定義的元組只有一個數(shù)據(jù)往声,那么這個數(shù)據(jù)后面也好添加逗號,否則數(shù)據(jù)類型為唯一的這個數(shù)據(jù)的數(shù)據(jù)類型
t2 = (10,)
print(type(t2)) # tuple
t3 = (20)
print(type(t3)) # int
t4 = ('hello')
print(type(t4)) # str
元祖常見操作
元祖數(shù)據(jù)不支持修改戳吝,只支持查找
烁挟,具體如下:
- 按下標(biāo)查號數(shù)據(jù)
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1[0]) # aa
- index(): 查找某個數(shù)據(jù),如果數(shù)據(jù)存在返回對應(yīng)的下標(biāo)骨坑,否則報錯,語法和列表柬采、字符串的index方法相同欢唾。
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.index('aa')) # 0
- count():統(tǒng)計某個數(shù)據(jù)在當(dāng)前元組出現(xiàn)的次數(shù)。
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.count('bb')) # 2
- len():統(tǒng)計元組中數(shù)據(jù)的個數(shù)粉捻。
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(len(tuple1)) # 4
注意:元組內(nèi)的直接數(shù)據(jù)如果修改則立即報錯
tuple1 = ('aa', 'bb', 'cc', 'bb')
tuple1[0] = 'aaa'
元組的修改
但是如果元組里面有列表礁遣,修改列表里面的數(shù)據(jù)則是支持的,故自覺很重要肩刃。
tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30)
print(tuple2[2]) # 訪問到列表
# 結(jié)果:(10, 20, ['aaaaa', 'bb', 'cc'], 50, 30)
tuple2[2][0] = 'aaaaa'
print(tuple2)
元組總結(jié)
- 定義元祖
t1 = (10, 20, 30)
t2 = (100,)
- 常用操作方法
- index()
- len()