Python开发快速上手
Python虽然有很多可以吐槽的地方,但是它的流行度及开发速度还是非常友好的,之后有机会或许能用得上。
f-string格式化字符串
简单的说,f-string可展示变量、计算表达式和调用函数,即:
f"display {variable}"
f"evaluate {expression}"
f"call {function}"name = "Alice"
grade = 6
f"{name} is in grade {grade}"自定义格式:{content:format}
千位分隔符
n = 10000000
f"{n:,}" # 10,000,000
f"{n:_}" # 10_000_000格式化日期时间
import datetime
now = datetime.datetime.now()
f"{now:%Y-%m-%d %H:%M:%S}"整数进制转换
n = 222
f"{n:d}" # 222
f"{n:b}" # 11011110
f"{n:#b}" # 0b11011110
f"{n:o}" # 336
f"{n:#o}" # 0o336
f"{n:x}" # de
f"{n:#x}" # 0xde
f"{n:X}" # DE
f"{n:#X}" # 0XDE格式化浮点数
value = 12.345
f"{value:.2f}" # 12.34,注意5没有进位
f"{value:.5f}" # 12.34500
value = 12.3451
f"{value:.2f}" # 12.35,注意5进位了,因为后面还有数字使用Decimal做到数学上的四舍五入:
import decimal
decimal.getcontext().rounding = "ROUND_HALF_UP"
value = 12.345
result = decimal.Decimal(value).quantize(decimal.Decimal("0.00"))
f"{result}"格式化宽度
for i in range(1, 11):
print(f'{i:02} {i*i:3} {i*i*i:4}')
01 1 1
02 4 8
03 9 27
04 16 64
05 25 125
06 36 216
07 49 343
08 64 512
09 81 729
10 100 1000字符串对齐
{s:[=][<^>][N]}
= 表示对齐填充符
< 表示左对齐,默认行为
^ 表示居中对齐
> 表示右对齐
N 表示长度,当字符串长度超过N时,原样显示字符串
s1 = "1"
s2 = "12345"
s3 = "123456789"
f"{s1:=<5}" # 1====
f"{s2:=<5}" # 12345
f"{s3:=<5}" # 123456789
f"{s1:=>5}" # ====1
f"{s1:=^5}" # ==1==Python内置函数
- abs(x) 返回绝对值
- bin(x) 返回整数的二进制
- bool(x) 返回对或错
- chr(i) 返回整数的字符形式
chr(97) is 'a' - divmod(a, b) 返回整除和余数
divmod(5, 2) is (2, 1) - hex(x) 返回整数的十六进制
- input() 输入
- int(x, base=10) 转换成整数,或将非十进制转换成十进制
int("123") is 123; int("110", 2) is 6 - isinstance(object, classinfo) 返回True如果object是classinfo的直接、间接、虚拟实例
- issubclass(class, classinfo)
- len(s) 返回
s的长度,包括字符串、字节、元组、列表、字典、集合、range - max(a, b, c) 求最大值,也可以求数组元素最大值
- min(a, b, c) 求最小值,也可以求数组元素最小值
- oct(x) 求十进制和八进制形式
- ord(c) 返回字符的ASCII码
ord('a') is 97 - pow(base, exp) 求base的exp次方
- reversed(s) 反转s
- sorted(s) 排序
- str(x) 将x转成string
Python字符串操作
string模块
import string
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_letters
# abcdefghijklmnopqrstuvwxyz
string.ascii_lowercase
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_uppercase
# 0123456789
string.digits
# 0123456789abcdefABCDEF
string.hexdigits
# 01234567
string.octdigits
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
string.punctuation
# characters space, tab, linefeed, return, formfeed, and vertical tab
string.whitespace
# all of above
string.printablePython字符串函数
help(str)
# 首字母大写,其他部分小写
str.capitalize()
# 大写变小写,小写变大写
str.swapcase()
# 是否prefix开头
str.startswith(prefix)
# 子串出现的次数
str.count(substr)
# 是否suffix结尾
str.endswith(suffix)
# 是否包含sub
str.find(sub)
# 是否只包含字母数字
str.isalnum()
# 是否只包含数字
str.isdecimal() # '0123'
str.isdigit() # '0123' '⅔' '2²'
str.isnumeric() # '0123' '⅔' '2²' 'ↁ', the last is Roman numerials
# 是否只包含字母
str.isalpha()
# 是否是小写字母,如果没有小写字母就是False
str.islower()
# 是否是大写字母,如果没有大写字母就是False
str.isupper()
# 转小写
str.lower()
# 转大写
str.upper()
# 去掉空格
str.strip()
str.lstrip()
str.rstrip()
# 移除前后相关的字符 abc: all chars a, b or c
str.lstrip(chars)
str.rstrip(chars)
# 移除前后子串 abc: only the 'abc' substr
str.removeprefix(substr)
str.removesuffix(substr)
# 将字符串用spe分割成3部分
str.partition(sep) # "abcdefg".partition("d") = ("abc", "d", "efg")
str.rpartition(sep)
# 替换子串
str.replace(old, new, count=-1)
# 查找子串
str.find(substr) # 查不到返回-1
str.rfind(substr)
str.index(substr) # 查不到抛出 ValueError
str.rindex(substr)
# 分割字符串
str.split(sep)
str.rsplit(sep, maxsplit=-1)Python列表函数
Python list 函数都是原地更新的,即list.reverse()没返回值,而是更新list本身。
help(list)
# 添加元素到列表最后
list.append(object)
# 返回浅拷贝
list.copy()
# 返回元素出现的次数
list.count(value)
# 扩展列表
list.extend(iterable)
# 返回元素第一次出现的位置
list.index(value, start=0, stop=9223372036854775807)
# 在某位置前插入元素
list.insert(index, object)
# 删除某位置的元素,空列表或超出列表长度时返回ValueError
list.pop(index)
# 删除第一次出现的value
list.remove(value)
# 反转列表
list.reverse()
# 列表排序
list.sort(reverse=False)Python字典
help(dict)
# 浅拷贝
dict.copy()
# 返回key的值
dict.get(key, default=None)
# 返回字典键值列表
dict.items() # {1: 2, 3: 4} => dict_items([(1, 2), (3, 4)])
# 返回键列表
dict.keys() # {1: 2, 3: 4} => dict_keys([1, 3])
# 返回键列表
dict.values() # {1: 2, 3: 4} => dict_values([2, 4])
# 删除key并返回value,若key不存在则返回default,否则KeyError
dict.pop(key[,default])
# 删除键值并返回
dict.popitems() # 返回 (key, value)Python 控制语句
If 条件语句
if x < 0:
print("small")
elif x == 0:
print("big")
else:
print("medium")For 循环
words = ["one", "two", "three"]
for word in words:
print(word)
...
one
two
three
=================================
words = ["one", "two", "three"]
for i in range(len(words)):
print(i, word[i])
...
0 one
1 two
2 threefor i in range(5):
print(i)
...
0
1
2
3
4
=================================
for i in range(2, 5):
print(i)
...
2
3
4
=================================
for i in range(0, 10, 3):
print(i)
...
0
3
6
9While 循环
a, b = 0, 1
while a < 10:
a, b = b, a+b
print(b)Match语句
status = http_status
match status:
case 200:
return "OK"
case 400:
return "Bad Request"
case 500:
return "Internal Error"Python项目初始配置
推荐使用pyproject.toml来管理项目,uv管理依赖,ruff格式化代码。
pyproject.toml文件内容
[project] name = "taishan" version = "0.1.0" requires-python = ">3.10" license = {file = "LICENSE"} description = "Taishan to proxy APIs of Taishan service" authors = [ {name = "Some Name", email = "[email protected]"}, ] dependencies = [ "fastapi>=0.115.6", "requests>=2.32.3", "uvicorn>=0.34.0", ] [project.urls] Repository = "https://github.com/chenzhiwei/python-quick-start" [project.optional-dependencies] dev = [ ] [project.scripts] taishan-cli = "taishan.cli:run" taishan-server = "taishan.server:run" [tool.ruff] line-length = 120 [tool.ruff.format] quote-style = "double" docstring-code-format = true [tool.ruff.lint.isort] case-sensitive = false force-sort-within-sections = false [tool.distutils.egg_info] egg_base = "build" [[tool.uv.index]] url = "https://mirrors.huaweicloud.com/repository/pypi/simple" default = true [build-system] requires = ["pdm-backend"] build-backend = "pdm.backend"uv命令
uv sync # 创建venv并安装依赖 source .venv/bin/activate uv add some-deps # 添加并安装依赖 taishan-cli # 运行项目命令 taishan-server # 运行项目服务 deactivateruff命令
ruff check src # 检查src目录中文件的格式及语法 ruff format src # 格式化src目录中的文件