python基本语法及使用

常用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() — 再拼接

1
print(input().strip())

不用循环语句的重复输出

使用*可以重复输出这段字符串

1
print(input() * 100)

截取字符串前 10 个字符

1
print(input()[0: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) # 暂停 3 秒

多线程

  1. 用函数创建线程

    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("所有任务完成")

  2. 用类来写线程(继承 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))

定义空函数

1
2
def nop():
pass

定义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)
# 需要转对应的编码,比如utf-8
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

# {"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}]}
# content = response.content.decode('utf-8')
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')          # 找到第一个 <p> 标签
soup.find_all('li') # 找到所有 <li> 标签
soup.find('div', {'class': 'container'}) # 通过属性查找标签

tag = soup.find('a')
tag.text # 获取文本
tag['href'] # 获取 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函数


python基本语法及使用
https://xiamu.icu/Python/python基本语法/
作者
肉豆蔻吖
发布于
2023年3月2日
许可协议