Python 字符串和 JS 类似,但有一些关键细节差异。
// 单引号、双引号、模板字面量
const s1 = 'hello';
const s2 = "world";
const s3 = `hi ${name}`;
// 多行字符串
const multi = `line1
line2
line3`;
# 单引号、双引号等价
s1 = 'hello'
s2 = "world"
# 三引号(多行字符串)
multi = """line1
line2
line3"""
# 原始字符串(不转义)
path = r"C:\Users\Alice"
' 和 " 完全等价,不像 JS 有模板字面量区分""" 写多行字符串,不需要反斜杠续行r"" 原始字符串等价于 JS 不需要额外处理(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" // 也不会报错,但也不会改变
| 方法 | 作用 | 示例 | 结果 |
|---|---|---|---|
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 是 Python 3.6+ 的字符串格式化方式,等价于 JS 的模板字面量,但功能更强。
const name = "Alice";
const age = 25;
console.log(`我叫${name},今年${age}岁`);
// 我叫Alice,今年25岁
// 表达式
console.log(`明年${age + 1}岁`);
name = "Alice"
age = 25
print(f"我叫{name},今年{age}岁")
# 我叫Alice,今年25岁
# 表达式
print(f"明年{age + 1}岁")
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(二进制)
x = 42
y = "hello"
# JS 中需要写:console.log(`x=${x}, y=${y}`)
# Python 3.8+ 可以简写:
print(f"{x=}, {y=}")
# x=42, y='hello'
# 自动带上变量名和值,调试非常方便
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]
[start:end:step] 非常强大,JS 的 slice() 只能处理 start/end,没有 step 参数。
Python 内置 re 模块,不需要额外安装。
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"
| 模式 | 含义 | 示例 |
|---|---|---|
\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"\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)
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") 也会匹配!
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 保留两位小数
# 三引号写多行字符串更方便
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"
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:]