Python虽然有很多可以吐槽的地方,但是它的流行度及开发速度还是非常友好的,之后有机会或许能用得上。
简单的说,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==
chr(97) is 'a'
divmod(5, 2) is (2, 1)
int("123") is 123; int("110", 2) is 6
s
的长度,包括字符串、字节、元组、列表、字典、集合、rangeord('a') is 97
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.printable
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 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)
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)
if x < 0:
print("small")
elif x == 0:
print("big")
else:
print("medium")
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 three
for 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
9
a, b = 0, 1
while a < 10:
a, b = b, a+b
print(b)
status = http_status
match status:
case 200:
return "OK"
case 400:
return "Bad Request"
case 500:
return "Internal Error"
推荐使用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 # 运行项目服务
deactivate
ruff命令
ruff check src # 检查src目录中文件的格式及语法
ruff format src # 格式化src目录中的文件