惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
MongoDB | Blog
MongoDB | Blog
H
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
V
V2EX
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
A
About on SuperTechFans
博客园_首页
L
LangChain Blog
量子位
雷峰网
雷峰网
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Jina AI
Jina AI
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
博客园 - 聂微东
Microsoft Azure Blog
Microsoft Azure Blog
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium

博客园 - 燕闪硕

EF Core 批量操作实战:3 种方案对比与性能测试 Python 开发 Windows 客户端:Web 技术做界面的 5 款核心工具 Python描述器(Descriptor)深度解析:OOP底层核心机制实操指南 使用pyenv-win管理多版本Python 利用canvas在手机页面实现景区导航的一点思路 重装系统后遇到Git Authentication failed 错误 [转帖]如何准确高效的获取数据库新插入数据的主键id [转帖]SQL中partition关键字的使用 利用分布类防止EF更新模型丢失验证信息 列表样式切换 CSS3 简易照片墙 HTML5表单增强 HTML5 元素拖放 HTML 5 全局属性 微软build 2015 写个程序登陆58同城 工厂方法 简单工厂 System.Data.SQLite兼容32位和64位问题
Python字符串编码及正则表达式使用
燕闪硕 · 2025-12-05 · via 博客园 - 燕闪硕

编码与解码

# 字符串编码为字节
text = "你好,燕闪硕!我在测试!"
utf8_bytes = text.encode("utf-8")
gbk_bytes = text.encode("gbk")

print(f"UTF-8编码: {utf8_bytes}")
print(f"GBK编码: {gbk_bytes}")

# 字节解码为字符串
decoded_text = utf8_bytes.decode("utf-8")
print(f"解码后: {decoded_text}")

# 处理编码错误
try:
    result = gbk_bytes.decode("utf-8")
except UnicodeDecodeError as e:
    print(f"解码错误: {e}")
    
# 使用错误处理策略
text_with_error = gbk_bytes.decode("utf-8", errors="ignore")
print(f"忽略错误解码: {text_with_error}")

正则表达式与字符串

import re

text = "我的电话是177-6901-8325,邮箱是792326016@qq.com"

# 查找电话号码
phone_pattern = r'\d{3}-\d{4}-\d{4}'
phones = re.findall(phone_pattern, text)
print(f"电话号码: {phones}")
# 替换敏感信息 censored = re.sub(r'\d{3}-\d{4}', 'XXX-XXXX', text) print(f"脱敏后: {censored}")
# 分割字符串 complex_text = "苹果,香蕉;橙子|葡萄" items = re.split(r'[,;|]', complex_text) print(f"分割结果: {items}")
# 匹配常见邮箱地址的正则表达式
email_regex = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
# 使用 findall 查找所有匹配的邮箱
text = """
联系方式:
张三的工作邮箱:zhangsan.company@example.com
李四的个人邮箱:lisi_123@gmail.com
测试邮箱:test.user+label@sub.domain.co.uk
无效示例:user@.com, @example.com, user@com
"""
found_emails = re.findall(email_regex, text)
print("找到的邮箱地址:")
for email in found_emails:
print(f" - {email}")

# 匹配网址
url = "https://www.baidu.com/index?name=test"
# 正则规则:匹配//后、/前的所有字符
domain_pattern = r"//([^/]+)"

在线正则测试工具 regex101.com