replace()
name = 'hello world haha'
new_name = name.replace('ha','Ha')
print(new_name)
name = 'hello world haha'
new_name = name.replace('ha','Ha',1)
print(new_name)
輸出:
hello world HaHa
hello world Haha
split():
以 str 為分隔符分割 name,如果 maxsplit 指定值,那么僅分割 maxsplit 個子串
name = 'hello world ha ha'
namr_list = name.split(" ")
print(namr_list)
name_list1 = name.split(" ", 2)
print(name_list1)
輸出:
['hello', 'world', 'ha', 'ha']
['hello', 'world', 'ha ha']
capitalize():
把字符串的一個字符大寫
title():
把每個單詞首字母大寫
startwith():
檢測字符串是否以S t r 為開頭
endswith():
檢測字符串是否以 str 為結(jié)尾
upper():
把字符串變?yōu)榇髮?/p>
lower():
把字符串變?yōu)樾?/p>
代碼塊:
my_str = 'hello world neuedu and neueducpp'
my_str2 = my_str.capitalize()
print(my_str2)
my_str2 = my_str.capitalize() #capitalize()的使用
print(my_str2)
my_str3 = my_str.title() # title()的使用
print(my_str3)
my_str4 = my_str.startswith('hello') # startwith()的使用
print(my_str4)
my_str5 = my_str.startswith('Hello')
print(my_str5)
my_str6 = my_str.endswith('cpp') # endswith()的使用
print(my_str6)
my_str7 = my_str.upper() # upper()的使用
print(my_str7)
my_str8 = my_str.lower() # lower() 的使用
print(my_str8)
輸出:
Hello world neuedu and neueducpp
Hello world neuedu and neueducpp
Hello World Neuedu And Neueducpp
True
False
True
HELLO WORLD NEUEDU AND NEUEDUCPP
hello world neuedu and neueducpp
rjust()
返回一個原字符串 右對齊 并用空格填充 w i d t h 長度的新字符串
ljust()
返回一個原字符串 左對齊 并用空格填充 w i d t h 長度的新字符串
lstrip():
刪除字符串左邊的空白字符
rstrip():
刪除字符串右邊的空白字符
strip():
刪除兩端的空白字符
代碼塊:
my_str_space = 'hello'
# rjust()返回一個原字符串 右對齊 并用空格填充 w i d t h 長度的新字符串
new_my_str_space = my_str_space.rjust(10,'$')
print(len(new_my_str_space))
print(new_my_str_space)
# ljust()返回一個原字符串 左對齊 并用空格填充 w i d t h 長度的新字符串
new_my_str_space1 = my_str_space.ljust(50,'*')
print(new_my_str_space1)
print(len(new_my_str_space1))#不常用
new_my_str_space2 = my_str_space.center(50,'$') # center()的使用
print(new_my_str_space2)
print(len(new_my_str_space2))
# lstrip() 除字符串左邊的空白字符
new_str2 = new_my_str_space2.lstrip()
print(new_str2)
print(len(new_str2))
# rstrip()字符串右邊的空白字符
new_str3 = new_str2.rstrip()
print(len(new_str3))
print(new_str3)
#strip() 刪除兩端的空白字符
print(len(new_my_str_space2))
new_str4 = new_my_str_space2.strip()
print(new_str4)
運行結(jié)果:
10
$$$$$hello
hello*********************************************
50
$$$$$$$$$$$$$$$$$$$$$$hello$$$$$$$$$$$$$$$$$$$$$$$
50
**********************hello***********************
50
**********************hello***********************
50
50
**********************hello***********************
50
**********************hello***********************
find()相似用法 ——rfind , lfind
my_str = 'hello world neuedu and neueducpp'
index5 = my_str.rfind('neuedu')
print(index5)
輸出:
23
index()相似用法——rindex
my_str = 'hello world neuedu and neueducpp'
index6 = my_str.index('neuedu')
print(index6)
輸出:
12
partition()相似用法——rpartition
把 mystr 以 str 分割成三部分 (str前,str,str后)
my_str = 'hello world neuedu and neueducpp'
print(my_str)
t_mystr = my_str.partition('neuedu')
print(t_mystr) #元組
輸出:
hello world neuedu and neueducpp
('hello world ', 'neuedu', ' and neueducpp')
splitlines():
line = 'hello\nworld'
print(line)
list_line = line.splitlines()
print(list_line)
輸出:
hello
world
['hello', 'world']
isalpha():
判斷字符串是否都是字母 Ture
my_str = 'hello world neuedu and neueducpp'
alpha = my_str.isalpha()
print(alpha)
alpha2 = 'wuyanzu' # 不能含有空格
alpha3 = alpha2.isalpha()
print(alpha3)
isdigit():
判斷判斷字符串是否都是數(shù)字 Ture
isalnum():
判斷是否只有字母或者數(shù)字
py_str1 = '1178824808@qq.com'
py_str2 = '1178824808qqcom'
py_str3 = '1178824808'
Judge1 = py_str1.isdigit() # 運用isdight()
print(Judge1)
Judge2 = py_str3.isdigit() # 運用isdight()
print(Judge2)
Judge3 = py_str1.isalnum() #運用 isalnum()
print(Judge3)
Judge4 = py_str2.isalnum() #運用isalnum()
print(Judge4)
輸出:
False
True
False
True
isspace():
join():
str4 = " "
list1 = ['my','name','is','wuyanzu']
# my_name = str4.join(list1)
# print(my_name)
my_name = "_".join(list1)
print(my_name)
my_name = "/".join(list1)
print(my_name)
輸出:
my_name_is_wuyanzu
my/name/is/wuyanzu
常用的字符串操作符:
find count repalce split join strip
內(nèi)容拓展:價值一個億的 AI 核心代碼
print('請輸入:')
while True:
print('AI智能說:'+input().strip('嗎?')+'!')
輸出:
請輸入:
在嗎?
AI智能說:在!
午飯吃了嗎
AI智能說:午飯吃了!
這篇文章贊了嗎?
AI智能說:這篇文章贊了!
列表
- 列表和數(shù)組 很像,但是數(shù)組可以儲存不同類型的數(shù)據(jù)
name_list = ['這個講的什么不重要!','重點是:shixiang Huang henshuai!',1024]
print('添加前:',name_list)
print(type(name_list))
#訪問
print(name_list[0])
# 遍歷
for name in name_list: # for循環(huán)特別重要
print(name)
輸出:
添加前: ['這個講的什么不重要!', '重點是:shixiang Huang henshuai!', 1024]
<class 'list'>
這個講的什么不重要!
這個講的什么不重要!
重點是:shixiang Huang henshuai!
1024
-
添加操作
append():
name_list = ['這個講的什么不重要!','重點是:shixiang Huang henshuai!',1024]
str = input('請輸入您要添加的內(nèi)容:')
name_list.append(str)
print('添加后:',name_list)
添加后: ['這個講的什么不重要!', '重點是:shixiang Huang henshuai!', 1024, '朋友,你好']
list1 = []
for i in range(10):
list1.append(i)
print(list1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
insert():
在指定位置index 前插入 元素 object;’
a = [0,1,2]
a.insert(1,10)
print(a)
輸出:
[0, 10, 1, 2]
extend():
可以將另外一個集合整體添加到列表中;
a = [1,2]
b = [3,4]
a.append(b)
print(a)
a.extend(b)
print(a)
輸出:
[1, 2, [3, 4]]
[1, 2, [3, 4], 3, 4]
-
修改
update():
修改操作
nname_list = ['這個講的什么不重要!','重點是:shixiang Huang henshuai!',1024]ame_list[1] = '我玩貂蟬很厲害~'
print(name_list)
輸出:
['這個講的什么不重要!', '我玩貂蟬很厲害~', 1024]
查找
in or not in
name_list = ['這個講的什么不重要!','重點是:shixiang Huang zeishuai!',1024]
find_name = '這個講的什么不重要'
if find_name in name_list:
print('在列表中')
else:
print('不在列表中')
不在列表中
刪除
del :根據(jù)下標進行刪除
pop :刪除最后一個元素
remove:根據(jù)元素的值進行刪除
name_list = ['這個講的什么不重要!','重點是:shixiang Huang zeishuai!',1024]
name_list.pop()
print('刪除后:',name_list)
刪除后: ['這個講的什么不重要!', '重點是:shixiang Huang zeishuai!']
列表的排序
語法:form modename import name1,name2
from random import randint
#num = randint(-10,10) #[-10,10]
#print(num)
num_list = []
for i in range(10):
num_list.append(randint(1,20))
print(num_list)
num_list.sort()
print('正序排序:',num_list)
num_list.sort(reverse = True)
print('逆序排序:',num_list)
new_list = sorted(num_list)
print(num_list)
print(new_list)
輸出:
[10, 1, 18, 20, 11, 16, 13, 9, 18, 18]
正序排序: [1, 9, 10, 11, 13, 16, 18, 18, 18, 20]
逆序排序: [20, 18, 18, 18, 16, 13, 11, 10, 9, 1]
[20, 18, 18, 18, 16, 13, 11, 10, 9, 1]
[1, 9, 10, 11, 13, 16, 18, 18, 18, 20]
sort() 與sorted()的區(qū)別
1) sort() 對原來的列表進行修改排序;sorted() 返回新的,原來的沒有;
2) sort() 屬于列表的成員方法;sorted()對所有可迭代對象進行操作;
3) ls.sort(key reverse); sorted(ls);
字符串的常用操作
print(dir(''))
print(dir([]))# 查找列表
python中的列表如下:
['add', 'class', 'contains', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'getnewargs', 'gt', 'hash', 'init', 'init_subclass', 'iter', 'le', 'len', 'lt', 'mod', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'rmod', 'rmul', 'setattr', 'sizeof', 'str', 'subclasshook', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
['add', 'class', 'contains', 'delattr', 'delitem', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'gt', 'hash', 'iadd', 'imul', 'init', 'init_subclass', 'iter', 'le', 'len', 'lt', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'reversed', 'rmul', 'setattr', 'setitem', 'sizeof', 'str', 'subclasshook', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
列表的嵌套 列表里面還有列表
school_name = [['qinghua','beida'],['nankai','tianda'],['dongda','yanshan']]
print(school_name)
print(school_name[0][1])
print('===========')
#print(school_name[0,1]) #此種寫法會報錯!
輸出:
[['qinghua', 'beida'], ['nankai', 'tianda'], ['dongqin', 'yanshan']]
beida
===========
列表推導式:
指輕量級的循環(huán)創(chuàng)建列表
list1 = []
for i in range(10):
list1.append(i)
print(list1)
from random import randint
list2 = [i for i in range(2,18,2)]
print(list2)
# 隨機創(chuàng)建一個列表
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8, 10, 12, 14, 16]
list3 = []
for _ in range(5):
list3.append("不給我魯班,我就送!")
print(list3)
list4 = ["不給我魯班,我就送!" for _ in range(3)]
print(list4)
輸出:
['不給我魯班,我就送!', '不給我魯班,我就送!', '不給我魯班,我就送!', '不給我魯班,我就送!', '不給我魯班,我就送!']
['不給我魯班,我就送!', '不給我魯班,我就送!', '不給我魯班,我就送!']
from random import randint
#生成10個元素,范圍在【-10,10】區(qū)間的列表
l = [randint(-10,10) for _ in range(10)]
print(l)
# 選出大于等于0的 數(shù)據(jù)
#選出大于等于0的 數(shù)據(jù)
res = []
for x in l:
if x >= 0:
res.append(x)
print('使用 for 循環(huán)篩選:',res)
# 循環(huán)的過程中使用 if
res2 = [x for x in l if x >= 0]
print('使用列推導式解析篩選:',res2)
輸出:
[-2, -8, 2, 6, -5, -6, -6, 6, -6, 4]
使用 for 循環(huán)篩選: [2, 6, 6, 4] # 這里介紹的兩種方法都十分重要,重點掌握
使用列推導式解析篩選: [2, 6, 6, 4]
- 列表轉(zhuǎn)化成字符串
my_list = ['Welcome','to','ML','world']
my_list_to = str(my_list)
print(my_list_to)
print(' '.join(my_list))
輸出:
['Welcome', 'to', 'ML', 'world']
Welcome to ML world
- 列表和字符串的 *
str1 = 'hehe'*3
print(str1)
list4 = ['6','9',0,3,14]*2
print(list4)
輸出:
hehehehehehe
['6', '9', 0, 3, 14, '6', '9', 0, 3, 14]
練習(1):使用for循環(huán)和列表推廣式篩選出偶數(shù)的數(shù)據(jù)
number = [i for i in range(11)]
print(number)
res3 = []
for x in number:
if x%2 == 0:
res3.append(x)
print('使用 for 循環(huán)篩選:',res3)
res4 = [x for x in number if x%2 == 0]
print('使用列推導式解析篩選:',res4)
輸出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
使用 for 循環(huán)篩選: [0, 2, 4, 6, 8, 10]
使用列推導式解析篩選: [0, 2, 4, 6, 8, 10]
練習(2):一個學校,有3個辦公室,現(xiàn)有8個老師等待工位分配,請編寫程序,完成隨機分配
from random import randint
import string
#定義3個辦公室
offices = [[],[],[]]
#定義8個老師
names = list(string.ascii_uppercase[:8])
#names = list(names)
print('八位老師的代號為:',names)
for name in names:
#[0~2] 產(chǎn)生隨機數(shù)
index = randint(0,2)
offices[index].append(name)
print('辦公室的分配情況:',offices)
i = 1
for tempNames in offices:
print('辦公室{}人數(shù)為{}'.format(i,len(tempNames)))
i += 1
print('成員為:') # 遍歷
for name in tempNames:
print('{}'.format(name),end=' ')
print('\n')
print('¥ '*10)
輸出:
八位老師的代號為: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
辦公室的分配情況: [['C'], ['A', 'E'], ['B', 'D', 'F', 'G', 'H']]
辦公室1人數(shù)為1
成員為:
C
¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥
辦公室2人數(shù)為2
成員為:
A E
¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥
辦公室3人數(shù)為5
成員為:
B D F G H
¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥
元組 tuple
代碼塊:
a = ('wuyanzu',111,0.88)
print(type(a)) # 查看 a 的類型
print(a[0])
# 修改 : 不能修改 也不能刪除
# a[1] = 99.9
# index count
a = ('a','b','c','b','a')
index1 = a.index('a')
print(index1)
c = a.count('b')
print(c)
輸出:
<class 'tuple'>
wuyanzu
0
2
注意:單個元素的元組后面有逗號隔開
b = (100,)
print(type(b))
<class 'tuple'>
同時遍歷兩個列表
zip() : 用于將可迭代對象作為參數(shù),將對象中的對應(yīng)元素壓縮;
一個元組,返回這些元組對象,節(jié)約內(nèi)存;
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
zipped = zip(a,b)
print(zipped)
print(list(zipped))
zipped1 = zip(a,c)
print(list(zipped1))
長度不一致時,與最短的對象相同
輸出:
<zip object at 0x000001B33FD37B88> #zip 不能直接輸出
[(1, 4), (2, 5), (3, 6)]
[(1, 4), (2, 5), (3, 6)]
字典
字典 key ==> value
info = {'name':'劉強東','age': 45, 'id': 2134254656,'address':'北京'}
#訪問 根據(jù)鍵進行訪問;
print(type(info))
print(info['name'])
# print(info['sex']) #訪問不存在的鍵,會報錯!
age = info.get('age',30)
#當我們不確定字典中是否存在某個key ,而且還要獲得其 value 可以使用get方法
print(age)
mail = info.get('mail','12qiangdong@jingdong.com')
print(mail)
#修改
info['name'] = '馬云'
print('修改后:',info)
#添加
info['sex'] = 'man'
print('添加后:',info)
#刪除 del 根據(jù) key 刪除
del info['name']
print('刪除后:',info)
#完全刪除
# del info
# print(info) #會報錯!
info.clear()
print('after clear:',info) # 輸出空字典
輸出:
<class 'dict'>
劉強東
45
12qiangdong@jingdong.com
修改后: {'name': '馬云', 'age': 45, 'id': 2134254656, 'address': '北京'}
添加后: {'name': '馬云', 'age': 45, 'id': 2134254656, 'address': '北京', 'sex': 'man'}
刪除后: {'age': 45, 'id': 2134254656, 'address': '北京', 'sex': 'man'}
after clear: {}
字典常用操作
代碼塊:
info = {'name':'劉強東','age': 45, 'id': 2134254656,'address':'北京'}
print(len(info)) # key 的個數(shù)
#keys
keys = info.keys()
print(keys)
#values
values = info.values()
print(values)
#items => (keys,values)
items = info.items()
print(items)
#遍歷
for key, value in info.items():
print(key,'==>>',value)
輸出:
4
dict_keys(['name', 'age', 'id', 'address'])
dict_values(['劉強東', 45, 2134254656, '北京'])
dict_items([('name', '劉強東'), ('age', 45), ('id', 2134254656), ('address', '北京')])
name ==>> 劉強東
age ==>> 45
id ==>> 2134254656
address ==>> 北京
集合
特點:無序,元素唯一
用途:元組 或 列表 去重
info = {'name':'劉強東','age': 45, 'id': 2134254656,'address':'北京'}
set1 = set()
set1 = {1, 2, 4, 5}
print(type(set1))
#添加 add
set1.add(8)
print(set1)
# 刪除 若不存在,會報錯
set1.remove(4)
print(set1)
# pop :隨機刪除集合中的元素
set1.pop()
print(set1)
# discard : 存在則直接刪除;不存在,也不會報錯
set1.discard(3)
print(set1)
輸出:
<class 'set'>
{1, 2, 4, 5, 8}
{1, 2, 5, 8}
{2, 5, 8}
{2, 5, 8}
name ==>> 劉強東
age ==>> 45
id ==>> 2134254656
address ==>> 北京
- 字典解析
創(chuàng)建一個班級的分數(shù)的隨機分布情況
from random import randint #使用隨機函數(shù)
grades = {'sutdent{}'.format(i):randint(50,100) for i in range(1,21)}
print(grades)
# 篩選數(shù)據(jù),選出高于90分的人
data = {k:v for k, v in grades.items() if v >=90}
print('10個人中成績 >= 90的人數(shù):',len(data),'個')
print(data)
# 學生成績隨機生成,可用于成績模擬
輸出:
# 隨機生成的結(jié)果
{'sutdent1': 75, 'sutdent2': 64, 'sutdent3': 91, 'sutdent4': 72, 'sutdent5': 79, 'sutdent6': 93, 'sutdent7': 80, 'sutdent8': 79, 'sutdent9': 68, 'sutdent10': 68, 'sutdent11': 65, 'sutdent12': 81, 'sutdent13': 93, 'sutdent14': 69, 'sutdent15': 79, 'sutdent16': 79, 'sutdent17': 95, 'sutdent18': 78, 'sutdent19': 56, 'sutdent20': 53}
10個人中成績 >= 90的人數(shù): 4 個
{'sutdent3': 91, 'sutdent6': 93, 'sutdent13': 93, 'sutdent17': 95}
集合解析
from random import randint #使用隨機函數(shù)
set1 = {randint(0,20) for _ in range(20)}
print('隨機生成集合:',set1)
# 找到能被3 整除 的
res = { x for x in set1 if x%3 == 0}
print('其中能被3整除的:',res)
輸出:
隨機生成集合: {0, 1, 2, 3, 5, 6, 8, 12, 13, 15, 16, 17, 18}
其中能被3整除的: {0, 3, 6, 12, 15, 18}
函數(shù)
def 函數(shù)名():
pass
# def 函數(shù)名():
# pass
#函數(shù)名(num)
def caculateNum(num):
'''
計算1~num 之間的累加和
:param num: 累加和的末尾 #函數(shù)文檔(標注函數(shù)用途)
:return: 返回累加和
'''
res = 0
for i in range(1, num+1):
res += i
return res
res = caculateNum(100)
print(res)
5050