常用API
大小写
.lower() — 全部小写
.upper() — 全部大写
.title() — 各个字符的首字母大写
.capitalize() — 首字母大写
1 2 3 4
| name = input() print(name.lower()) print(name.upper()) print(name.title())
|
去除空格
.strip() — 删除两边空格
.lstrip() — 删除左边空格
.rstrip() — 删除右边空格
.replace(“ “,””) — 删除所有空格
.split() — 先切分,””.join() — 再拼接
不用循环语句的重复输出
使用*可以重复输出这段字符串
截取字符串前 10 个字符
list 列表的添加和移除
1 2 3 4 5 6 7 8 9
| offer_list = ['Allen', 'Tom'] for i in offer_list: print('{}, you have passed our interview and will soon become a member of our company.'.format(i))
offer_list.remove('Tom') offer_list.append('Andy')
for i in offer_list: print('{}, welcome to join us!'.format(i))
|
slice 切片函数
1 2 3 4 5
| group_list = [ 'Tom', 'Allen', 'Jane', 'William', 'Tony' ]
print(group_list[slice(0, 2)]) print(group_list[slice(1, 4)]) print(group_list[slice(3, 5)])
|
与或非
1 2 3 4 5 6 7
| x, y = input().split()
print(x and y) print(x or y) print(not int(x)) print(not int(y))
|
成员与列表 in
1 2 3 4
| line = input().split() name = input()
print(name in line)
|
sleep函数
sleep() 是 Python 中用来 让程序暂停执行一段时间 的函数,来自内置的 time 模块。
1 2 3
| import time
time.sleep(3)
|
多线程
用函数创建线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import threading import time
def task(name): print(f"[{name}] 任务开始") time.sleep(2) print(f"[{name}] 任务结束")
t1 = threading.Thread(target=task, args=("线程1",)) t2 = threading.Thread(target=task, args=("线程2",))
t1.start() t2.start()
t1.join() t2.join()
print("所有任务完成")
|
用类来写线程(继承 Thread)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import threading import time
class MyThread(threading.Thread): def __init__(self, name): super().__init__() self.name = name def run(self): print(f"[{self.name}] 线程启动") time.sleep(1) print(f"[{self.name}] 线程结束")
t1 = MyThread("线程A") t2 = MyThread("线程B")
t1.start() t2.start()
t1.join() t2.join()
|
🎯 应用场景举例
- 模拟多个用户同时抢票
- 同时发多个网络请求
- 批量下载文件
- 多个文件同时读取或写入
for循环
1 2
| for i in range(1, 6): print(i)
|
输出1-5,不包含6
function函数 和 if条件
定义函数使用def关键字
1 2 3 4 5 6 7
| def my_abs(x): if x >= 0: return x else: return -x
print(my_abs(-99))
|
定义空函数
定义main函数
1 2
| if __name__ == "__main__": main()
|
requests的基本使用
现成的工具
https://curlconverter.com/
1 2 3 4 5 6
| import requests
response = requests.get(url=url, params=params, cookies=cookies, headers=headers)
content = response.content.decode('utf-8')
|
json操作
content转换完毕之后可能需要再转成json对象,使用 json.loads
函数进行转换成dict对象
1 2 3 4 5 6 7 8 9 10 11 12 13
|
import json
content = '{"status": "1", "state": "success", "data": [{"value": 7642}, {"value": 5199}, {"value": 4247}, {"value": 4604}, {"value": 3344}, {"value": 9769}, {"value": 6655}, {"value": 1263}, {"value": 3209}, {"value": 5533}]}' print(content) obj = json.loads(content) data_list = obj['data'] for d in data_list: value = d['value'] print(value)
|
BeautifulSoup 解析html
pip install beautifulsoup4
去除标签后的纯文本
1 2 3 4 5 6 7 8 9 10 11 12 13
| from bs4 import BeautifulSoup
def html_to_text(html: str) -> str: """ 将 HTML 内容转换为纯文本,保留基本换行结构。
:param html: 原始 HTML 字符串 :return: 去除标签后的纯文本 """ soup = BeautifulSoup(html, 'html.parser') text = soup.get_text(separator='\n') return text.strip()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| soup.find('p') soup.find_all('li') soup.find('div', {'class': 'container'})
tag = soup.find('a') tag.text tag['href']
soup.find('div').find('span').text
for li in soup.find_all('li'): print(li.text)
|
读写文件
写文件
1 2 3 4 5 6 7 8 9
| with open('example.txt', 'w', encoding='utf-8') as f: f.write("这是写入的第一行\n") f.write("这是第二行\n")
with open('example.txt', 'a', encoding='utf-8') as f: f.write("追加一行内容\n")
|
读文件
1 2 3 4 5 6 7 8 9
| with open('example.txt', 'r', encoding='utf-8') as f: content = f.read() print(content)
with open('example.txt', 'r', encoding='utf-8') as f: for line in f: print(line.strip())
|
连接数据库
调用JS函数