目录

Python cheatsheet

Python速查手册 大部分是标准库,对于画图和scipy等另开一篇

[TOC]

字符串

分割

  • split

拼接

  • join

替换修改

  • replace
  • strip 去除字符串前后的空格

格式化

  • Python3推荐使用f string,更自然、简洁,语法就是加一个f
1
2
3
>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'

要格式化就是冒号+数字+点+数字+字母

1
2
3
>>> a = 123.456
>>> f'a is {a:8.2f}'
'a is   123.46'

查找

一般不用字符串类的find函数,而是配合re类。

正则表达式

理论

编程

  • 使用re类
Function Description
findall (模式, 文本) Returns a list containing all matches,注意返回的是列表!
search (模式, 文本) Returns a Match object if there is a match anywhere in the string 但是只返回第一个
split (模式, 文本, k) Returns a list where the string has been split at each match 只作用k次
sub (模式, 待替换, 文本) Replaces one or many matches with a string

其中,search函数返回的match object额外携带了一些信息,比如

.span() 指明了匹配文本的起始和结束位置 .string 返回被匹配字符串 .group() 返回匹配的文本

如果想要返回所有匹配的文本和它们的位置?

  • finditer函数返回一个包含所有Match Object的list

Collections

Python的collections,包含了listsetdictionarytuple四大类

列表

切片,前开后闭

字典

构造

更新

元组

这篇文章有讲,有两种看待方式

文件

OOP

  • TODO

迭代器

基本

yield

⭐开一个python终端能做的事情

  • scipy 求导求积分