字符串常量
python 标准库
- join方法
','.join(["a", "b"])
- 切片
"abcdefg"[::1]
- len
- in
- str.split()
- 大小写
upper
lower
isupper
islower
swapcase # 交换大小写
capitalize # 首字母大写
istitle # 是否是标题(所有单词首字母大写)
- 判断
isalpha
isalnum
isspace
isdecimal
-
startwith endwith
-
查找
find
index
rfind
rindex
- 操作
join
split
strip
rstrip
lstrip
replace
- Counter 类
from collections import Counter
c = Counter('abcba')
# c Counter({'a':2, 'b':2, 'c':1})
# 字典设置默认键值对,存在则不操作
{}.setdefault("a", 0)
- 字符串格式化
str.format()
正则
# 编译版本的正则表达式速度更快
import re
re.split()
re.findall()
re.compile()
re.match()
re.finditer()
re.sub()
re.IGNORECASE
字符集编码
# python2 解 unicode 的方法
f.decode('unicode-escape')
codecs
当需要频繁进行读取文件并且进行编码转译时,可以用该模块,指定编码格式(在python3中open函数已经支持该操作)
import codecs
f = codecs.open("123.txt", "w", encoding="utf-8")
jinja2
-
语法块
- 控制结构 {% %}
- 变量取值 {{ }}
- 注释 {# #}
{% if users %} <ul> {% for user in users %} <li>{{ user.username }}</li> {% endfor %} </ul> {% endif %}
-
变量
<p>{{ mydict["key"] }}</p> <p>{{ mylist[index] }}</p> <p>{{ myobj.method() }}</p>
-
过滤器
- safe
- capialize 首字母大写,其它小写
- lower
- upper
- title
- trim 去掉首尾的空格
- striptags 去掉html标签
- join
- replace
- round
- int
{{ "hello word" | replace("hello", "goodby") | title }}
-
控制结构
{% if kenny.sick %} kenny is sick {% elif kenny.dead %} you killed kenny! you basrard!!! {% else %} kenny looks okay --- so far {% endif %}
-
for 循环
<ul> {% for user in users %} <li>{{ user.username }}</li> {% enffor %} </ul>
for 循环中包含一些特殊变量
- loop.index
- loop.index0
- loop.revindex
- loop.revindex0
- loop.first
- loop.last
- loop.length
- loop.cycle
-
宏
类似编程中的函数{# 定义 #} {% macro input(name, type='text', value='') %} <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> {% endmacro %} {# 调用 #} <p>{{ input('username', value="user") }}</p> <p>{{ input('passwd', 'passwd') }}</p> <p>{{ input('submit', 'submit', 'submit') }}</p>
-
继承 和 super 函数
- base.html
<html lang="en"> <head> {% block head %} <link rel="stylesheet" href="style.css" /> <title>{% bolck title %}{% endblock %}-My Webpage</title> {% endblock %} </head> <body> <div> {% block content %}{% endblock %} </div> </body>
- index.html
{% extends "base.html" %} {% bolck title %}Index{% endblock %} {% block head %} {{ super }} <style type="text/css"> .important {color: #336699} </style> {% endblock %} {% block content %} <h1>Index</h1> <p class="important"> hellow world. </p> {% endblock %}
-
其它运算
- 算数运算 + - * / // % **
- 比较运算 == != > >= < <=
- 逻辑运算 not and or