第 16 章 / 70 · 基础 · 常用标准库
string 模块
字符串常量与模板
先介绍1 个 demo6 个任务答案可展开
一、本章介绍
string 模块提供常用字符串常量:ascii_letters 字母表、digits 数字、punctuation 标点,还有 Template 安全模板。
这一章从常量使用到验证码生成,再到模板替换。
本章要点
- ascii_letters / digits
- punctuation 标点
- Template 模板
- 常量组合字符集
二、先看 demo
下面这个例子把本章涉及的用法尽量全面地串了一遍,代码带逐行注释,可以直接复制到本地 .py 文件运行。
案例
先看一个完整例子
介绍 · 逐行注释import string
from string import Template
print(len(string.ascii_letters))
print(string.digits)
print(string.punctuation[:5])
t=Template("你好,$name")
print(t.substitute(name="小明"))运行结果
52
0123456789
!"#$%
你好,小明要点:ascii_letters 是 52 个字母,digits 是 10 个数字;Template 用 $变量 占位。
三、6 个任务(自己先写,再看答案)
难度从入门到挑战逐步增加。每个任务的答案默认折叠,点开可看参考代码、运行结果;有第二种解法的也一并给出。代码都可以直接运行。
任务 1
字母表长度
自己写 · 附答案入门 ★☆☆解题提示:本题主要用到 ascii_letters / digits、punctuation 标点、Template 模板。先对照要求自己写一遍,卡住了再展开答案。
打印 ascii_lowercase 的长度
参考答案(先自己写,再看)
参考答案一
import string
print(len(string.ascii_lowercase))运行结果
26参考答案二(另一种解法)
import string
print(len(string.ascii_uppercase))任务 2
拼接字符集
自己写 · 附答案入门 ★☆☆解题提示:本题主要用到 ascii_letters / digits、punctuation 标点、Template 模板。先对照要求自己写一遍,卡住了再展开答案。
把大小写字母和数字拼成一个字符串并打印长度
参考答案(先自己写,再看)
参考答案一
import string
cs=string.ascii_letters+string.digits
print(len(cs))运行结果
62参考答案二(另一种解法)
import string
print(len(string.ascii_letters+string.digits))任务 3
数字判断
自己写 · 附答案进阶 ★★☆解题提示:本题主要用到 ascii_letters / digits、punctuation 标点、Template 模板。先对照要求自己写一遍,卡住了再展开答案。
判断 "a1b2" 里有几个数字字符
参考答案(先自己写,再看)
参考答案一
import string
s="a1b2"
print(sum(c in string.digits for c in s))运行结果
2参考答案二(另一种解法)
print(sum(c.isdigit() for c in "a1b2"))任务 4
模板替换
自己写 · 附答案进阶 ★★☆解题提示:本题主要用到 ascii_letters / digits、punctuation 标点、Template 模板。先对照要求自己写一遍,卡住了再展开答案。
用 Template 把 "$name 考了 $score 分" 替换为 小明 和 90
参考答案(先自己写,再看)
参考答案一
from string import Template
t=Template("$name 考了 $score 分")
print(t.substitute(name="小明",score=90))运行结果
小明 考了 90 分参考答案二(另一种解法)
print("{} 考了 {} 分".format("小明",90))任务 5
安全替换
自己写 · 附答案挑战 ★★★解题提示:本题主要用到 ascii_letters / digits、punctuation 标点、Template 模板。先对照要求自己写一遍,卡住了再展开答案。
用 safe_substitute 替换 "Hi $name, $other" 只提供 name
参考答案(先自己写,再看)
参考答案一
from string import Template
t=Template("Hi $name, $other")
print(t.safe_substitute(name="Tom"))运行结果
Hi Tom, $other参考答案二(另一种解法)
print("Hi Tom, $other")任务 6
生成验证码
自己写 · 附答案挑战 ★★★解题提示:本题主要用到 ascii_letters / digits、punctuation 标点、Template 模板。先对照要求自己写一遍,卡住了再展开答案。
用 random+string 生成 4 位纯数字验证码(seed=1)
参考答案(先自己写,再看)
参考答案一
import random,string
random.seed(1)
print("".join(random.sample(string.digits,4)))运行结果
2140参考答案二(另一种解法)
import random,string
random.seed(1)
print("".join(random.sample(string.digits,4)))