Day 5 · 字符串、格式化与 f-string

Week 1 · Day 5 / 56 · 返回大纲

一、字符串基础

Python 字符串和 JS 类似,但有一些关键细节差异。

1.1 创建和类型

JavaScript
// 单引号、双引号、模板字面量
const s1 = 'hello';
const s2 = "world";
const s3 = `hi ${name}`;

// 多行字符串
const multi = `line1
line2
line3`;
Python
# 单引号、双引号等价
s1 = 'hello'
s2 = "world"

# 三引号(多行字符串)
multi = """line1
line2
line3"""

# 原始字符串(不转义)
path = r"C:\Users\Alice"
关键差异:

1.2 字符串是不可变的

⚠️ Python 字符串不可变,和 JS 一样:
s = "hello"
s[0] = "H"  # TypeError: 'str' object does not support item assignment

# 正确做法:创建新字符串
s = "H" + s[1:]  # "Hello"
s = s.replace("h", "H")  # "Hello"

# JS 中同样不可变
# s[0] = "H"  // 也不会报错,但也不会改变

1.3 常用方法一览

方法作用示例结果
upper()转大写"abc".upper()"ABC"
lower()转小写"ABC".lower()"abc"
strip()去首尾空白" hi ".strip()"hi"
lstrip()去左侧空白" hi".lstrip()"hi"
rstrip()去右侧空白"hi ".rstrip()"hi"
replace(a, b)替换"hello".replace("l", "L")"heLLo"
split(sep)分割成列表"a,b,c".split(",")["a","b","c"]
join(list)列表拼接",".join(["a","b"])"a,b"
find(sub)查找位置"hello".find("ll")2
count(sub)计数"hello".count("l")2
startswith(prefix)开头匹配"hello".startswith("he")True
endswith(suffix)结尾匹配"hello".endswith("lo")True
isalpha()全字母"hello".isalpha()True
isdigit()全数字"123".isdigit()True
title()首字母大写"hello world".title()"Hello World"
zfill(width)零填充"42".zfill(5)"00042"

二、f-string 格式化(重点)

f-string 是 Python 3.6+ 的字符串格式化方式,等价于 JS 的模板字面量,但功能更强。

2.1 基本用法

JavaScript
const name = "Alice";
const age = 25;

console.log(`我叫${name},今年${age}岁`);
// 我叫Alice,今年25岁

// 表达式
console.log(`明年${age + 1}岁`);
Python
name = "Alice"
age = 25

print(f"我叫{name},今年{age}岁")
# 我叫Alice,今年25岁

# 表达式
print(f"明年{age + 1}岁")

2.2 数字格式化

pi = 3.14159265
print(f"{pi:.2f}")       # 3.14(保留2位小数)
print(f"{pi:.4f}")       # 3.1416(四舍五入)

big = 1000000
print(f"{big:,}")        # 1,000,000(千分位)

rate = 0.156
print(f"{rate:.1%}")     # 15.6%(百分比)

# 宽度和对齐
print(f"{'左':<10}")      # 左对齐(默认)
print(f"{'右':>10}")      # 右对齐
print(f"{'中':^10}")      # 居中

# 填充
print(f"{42:05d}")       # 00042(零填充)
print(f"{42:x}")         # 2a(十六进制)
print(f"{42:b}")         # 101010(二进制)

2.3 调试用法(Python 3.8+)

x = 42
y = "hello"

# JS 中需要写:console.log(`x=${x}, y=${y}`)
# Python 3.8+ 可以简写:
print(f"{x=}, {y=}")
# x=42, y='hello'

# 自动带上变量名和值,调试非常方便

三、字符串切片(和 JS 对比)

s = "Python"

s[0]       # "P"(第一个字符)
s[-1]      # "n"(最后一个字符)
s[0:3]     # "Pyt"(前3个字符)
s[3:]      # "hon"(从索引3到末尾)
s[:3]      # "Pyt"(从开头到索引3)
s[::-1]    # "nohtyP"(反转字符串!)

# JS 对比:
# s.slice(0, 3)    // "Pyt"
# s.slice(3)       // "hon"
# [...s].reverse().join('')  // 反转,麻烦很多

# Python 反转字符串极简:
reversed_s = s[::-1]
💡 前端类比: Python 的切片 [start:end:step] 非常强大,JS 的 slice() 只能处理 start/end,没有 step 参数。

四、正则表达式入门

Python 内置 re 模块,不需要额外安装。

4.1 四个核心函数

import re

# 1. match:从头匹配
result = re.match(r"hello", "hello world")
# 匹配成功,result 是 Match 对象
# re.match(r"world", "hello world")  # None(不在开头)

# 2. search:搜索任意位置
result = re.search(r"world", "hello world")
# 匹配成功

# 3. findall:找所有匹配
text = "电话:13812345678 和 13987654321"
phones = re.findall(r"1\d{10}", text)
# ['13812345678', '13987654321']

# 4. sub:替换
text = "2026-09-22"
new_text = re.sub(r"-", "/", text)
# "2026/09/22"

4.2 常用模式

模式含义示例
\d数字\d{3} 匹配3个数字
\w字母数字下划线\w+ 匹配单词
\s空白字符\s+ 匹配空格/tab
.任意字符除换行外
*0次或多次ab*c 匹配 ac/abc/abbc
+1次或多次ab+c 匹配 abc/abbc
?0次或1次ab?c 匹配 ac/abc
^开头^hello 行首匹配
$结尾world$ 行尾匹配
⚠️ 原始字符串 r"": 正则中经常有反斜杠,Python 用 r"\d" 而不是 "\\d",避免转义地狱。这和 JS 中正则直接写一致。

五、实战:文本处理工具

创建 day5.py:

#!/usr/bin/env python3
"""Day 5 练习:文本分析工具"""
import re

def analyze_text(text):
    """分析一段文本的统计信息"""
    # 基本统计
    char_count = len(text)
    word_count = len(text.split())
    line_count = len(text.splitlines()) if text else 0

    # 找邮箱
    emails = re.findall(r"\w+@\w+\.\w+", text)

    # 找手机号
    phones = re.findall(r"1[3-9]\d{9}", text)

    # 找 URL
    urls = re.findall(r"https?://\S+", text)

    # 输出报告
    print("=" * 40)
    print(f"字符数:{char_count}")
    print(f"单词数:{word_count}")
    print(f"行数:{line_count}")
    print(f"邮箱:{emails if emails else '无'}")
    print(f"手机号:{phones if phones else '无'}")
    print(f"URL:{urls if urls else '无'}")
    print("=" * 40)

# 测试
sample = """
Hello! Contact us at support@example.com or 13812345678.
Visit https://docs.python.org for more info.
Another email: admin@hellochange.cn
"""

analyze_text(sample)

动手练习

练习 1:手机号验证
写一个函数验证中国手机号是否合法(1开头,第二位3-9,共11位)
def validate_phone(phone):
    """验证手机号"""
    import re
    pattern = r"^1[3-9]\d{9}$"
    return bool(re.match(pattern, phone))

# 测试
print(validate_phone("13812345678"))  # True
print(validate_phone("12345678901"))  # False
print(validate_phone("1381234567"))   # False(只有10位)
查看答案
参考答案
def validate_phone(phone):
    import re
    # ^ 开头,$ 结尾,确保完整匹配
    return bool(re.match(r"^1[3-9]\d{9}$", phone))

# 不加 ^$ 的坑:
# re.match(r"1[3-9]\d{9}", "13812345678999") 也会匹配!
练习 2:文本模板渲染
用 f-string 渲染一个邮件模板
def render_email(name, product, amount, date):
    return f"""亲爱的 {name}:

感谢您购买 {product}。
订单金额:¥{amount:.2f}
下单日期:{date}

祝您生活愉快!
"""

print(render_email("张三", "Python 教程", 99.5, "2026-09-22"))
查看答案
参考答案
def render_email(name, product, amount, date):
    return f"亲爱的{name}:感谢购买{product},金额¥{amount:.2f},日期{date}"

# 注意::.2f 保留两位小数
# 三引号写多行字符串更方便
练习 3:字符串反转
接收一个字符串,反转后输出
def reverse_text(text):
    return text[::-1]

print(reverse_text("Python"))  # nohtyP
查看答案
参考答案
# Python 反转字符串超级简单
text = "Hello World"
reversed_text = text[::-1]
# JS 需要:[...text].reverse().join('')

# 按单词反转
words = "Hello World Python"
result = " ".join(words.split()[::-1])
# "Python World Hello"
练习 4:数据脱敏
把手机号中间4位替换成 ****
def mask_phone(phone):
    """13812345678 → 138****5678"""
    import re
    return re.sub(r"(\d{3})\d{4}(\d{4})", r"\1****\2", phone)

print(mask_phone("13812345678"))  # 138****5678
查看答案
参考答案
import re

def mask_phone(phone):
    # 分组:前3位 + 中间4位 + 后4位
    # \1 引用第一组,\2 引用第二组
    return re.sub(r"(\d{3})\d{4}(\d{4})", r"\1****\2", phone)

# 不使用正则的做法:
def mask_phone_manual(phone):
    return phone[:3] + "****" + phone[7:]

打卡验收

理解 Python 字符串不可变,修改需创建新字符串
熟练使用 upper/lower/strip/replace/split/join
会用 f-string 格式化数字::.2f、:,、:.1%
会用 f-string 调试:f'{variable=}'
掌握字符串切片 [start:end:step],特别是反转 [::-1]
了解 re.match/re.search/re.findall/re.sub 四个核心函数
完成 4 个动手练习,代码能跑通
能向别人解释 f-string 和 JS 模板字面量的异同
打卡方式: 全部勾选后,告诉我 "Day 5 打卡",并贴出你的代码。