答案:Python提取字符串可根据位置用切片、按分隔符用split()、通过find()定位、用正则提取复杂内容、或使用strip()等方法处理文本,如提取邮箱、电话、文件名等。

Python 提取字符串内容有多种方式,具体方法取决于你想提取什么类型的内容。以下是几种常见场景和对应的操作方法。
如果你知道要提取的字符在字符串中的位置,可以使用字符串切片:
text = "Hello, my name is Alice" # 提取前5个字符 print(text[0:5]) # 输出: Hello <h1>提取第17到22个字符</h1><p>print(text[17:22]) # 输出: Alice</p><h1>倒序提取最后5个字符</h1><p>print(text[-5:]) # 输出: Alice</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>
使用 split() 方法可以根据分隔符拆分字符串,提取部分内容:
text = "name=Alice;age=30;city=Beijing"
<h1>按分号分割</h1><p>parts = text.split(";")
print(parts) # ['name=Alice', 'age=30', 'city=Beijing']</p><h1>提取 city 的值</h1><p>for part in parts:
if "city" in part:
city = part.split("=")[1]
print(city) # 输出: Beijing</p>查找某个子串的位置,再结合切片提取后续内容:
text = "User email: alice@example.com was logged in"
<p>start = text.find("email: ") + len("email: ")
end = text.find(" ", start)</p><p>email = text[start:end]
print(email) # 输出: alice@example.com</p>对于格式不固定但有规律的内容(如邮箱、电话、日期),推荐使用 re 模块:
import re
<p>text = "Contact us at support@company.com or call +1-800-123-4567"</p><h1>提取邮箱</h1><p>email = re.search(r"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}\b", text)
if email:
print(email.group()) # 输出: support@company.com</p><h1>提取电话号码</h1><p>phone = re.search(r"+\d{1,3}-\d{3}-\d{3}-\d{4}", text)
if phone:
print(phone.group()) # 输出: +1-800-123-4567</p>比如提取文件名、后缀、去除空格等:
filename = " document.pdf "
clean_name = filename.strip() # 去空格 → "document.pdf"
file_base = clean_name.split(".")[0] # 提取主名 → "document"
file_ext = clean_name.split(".")[-1] # 提取后缀 → "pdf"
基本上就这些常用方法。根据你要提取的内容特点选择合适的方式:简单位置用切片,结构化用 split,模糊匹配用正则。不复杂但容易忽略细节。
以上就是Python如何提取字符串的内容的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号