Python开发快速上手

Python虽然有很多可以吐槽的地方,但是它的流行度及开发速度还是非常友好的,之后有机会或许能用得上。

Python项目初始配置

使用pyproject.toml来定义项目相信及依赖等。

[project]
name = "python-quick-start"
description = "Python Quick Start"
requires-python = ">=3.10"
license = "MIT"
authors = [
    { name = "Some Name", email = "[email protected]" },
]
dependencies = [
    "request",
]

[project.optional-dependencies]
dev = [
  "ruff",
]

[tool.ruff]
line-length = 110

初始配置:

python -m venv .venv
source .venv/bin/activate

# Install dependencies
pip install .

# Install optional dependencies
pip install .[dev]

deactivate

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.printable

Python字符串函数

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 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

While 循环

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"

Pipenv

Pipenv 算是 Python 官方的工具了,主要参考了 npm 的功能,我觉得思路挺不错的。

目前Pipenv的开发进度比较慢,并且和pyproject.toml也有点冲突,另外就是速度太慢了,暂时不太建议在项目中使用。

安装 Pipenv

sudo pip install pipenv
sudo apt install pipenv

开始一个新项目

mkdir python-quick-start
cd python-quick-start
mkdir .venv # implicitly set virtualenv location
pipenv shell
pipenv install pycodestyle black --dev

Pipfile 添加脚本

[scripts]
lint = "pycodestyle ."
code-diff = "black --diff ."
code-format = "black ."
main = "./main.py"

执行命令

pipenv run lint
pipenv run code-diff
pipenv run code-format
pipenv run main

参考