- Python 学习路径:从零到精通
- Python 环境搭建
- Python 基础语法
- Python 数据结构
- Python 字符串操作
- Python 文件读写
- Python 函数进阶
- Python 面向对象编程(OOP)
- Python 异常处理
- Python 模块与包
- Python 迭代器与生成器
- Python 装饰器
- Flask 基础与入门
- Django 框架基础
- Python RESTful API 开发
- Python Web 表单与用户认证
- Python 数据的操作
- SQLAlchemy ORM 的使用
- Pandas 数据分析基础
- Numpy 数值计算
- 数据可视化(Matplotlib, Seaborn)
- 数据导入导出(CSV, Excel, JSON)
- 使用 requests 库进行 HTTP 请求
- 使用 BeautifulSoup 或 Scrapy 进行网页解析
- 线程与进程的概念
- 使用 threading 模块实现多线程
- 使用 multiprocessing 模块实现多进程
- GIL(全局解释器锁)的概念与影响
- Python 自动化脚本
- Python 常用设计模式
- Python 性能分析工具
- Python 内存管理与优化
- 并行与异步编程(asyncio, concurrent.futures)
- 测试驱动开发(TDD)
- WebSocket 实时通信
- Python GraphQL API 开发
- 前后端分离与前端框架(Vue.js, React)的集成
- 使用 Docker 容器化部署 Python 应用
- CI/CD 流程的自动化(GitHub Actions, Jenkins)
- Scikit-learn, TensorFlow 或 PyTorch 的基础知识
- 数据预处理与特征工程
- 构建与训练模型
- 模型评估与调优
- Hadoop 与 Spark 基础
- 使用 PySpark 进行大数据处理
- 分布式计算与数据流处理
- 基本的加密与解密技术
- 简单的网络安全工具(如端口扫描、漏洞检测)
- Web 安全与常见攻击防御(如 SQL 注入、XSS)
- 项目的协作流程
- 撰写高质量的代码与文档
Python 字符串操作
class PythonPython 字符串操作详解
Python 字符串(str
)是不可变的序列类型,用于存储和操作文本。以下是 Python 中常见的字符串操作,包括连接、切片、格式化,以及常用的字符串方法和正则表达式的使用。
1. 字符串连接
使用 +
操作符:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出: "Hello World"
使用 join()
方法:
words = ["Hello", "World"]
result = " ".join(words)
print(result) # 输出: "Hello World"
2. 字符串切片
text = "Hello World"
# 切片从索引 0 到 4(不包括 5)
print(text[0:5]) # 输出: "Hello"
# 从索引 6 开始到末尾
print(text[6:]) # 输出: "World"
# 反向切片
print(text[-5:]) # 输出: "World"
# 步长切片(每隔一个字符)
print(text[::2]) # 输出: "HloWrd"
3. 字符串格式化
使用 %
操作符:
name = "Alice"
age = 30
text = "Name: %s, Age: %d" % (name, age)
print(text) # 输出: "Name: Alice, Age: 30"
使用 str.format()
方法:
text = "Name: {}, Age: {}".format(name, age)
print(text) # 输出: "Name: Alice, Age: 30"
使用 f-string (Python 3.6+):
text = f"Name: {name}, Age: {age}"
print(text) # 输出: "Name: Alice, Age: 30"
4. 字符串常用方法
-
split()
: 按指定分隔符拆分字符串text = "apple,banana,cherry" fruits = text.split(",") print(fruits) # 输出: ['apple', 'banana', 'cherry']
-
join()
: 用指定分隔符连接列表中的字符串fruits = ['apple', 'banana', 'cherry'] result = ", ".join(fruits) print(result) # 输出: "apple, banana, cherry"
-
replace()
: 替换字符串中的某部分text = "Hello World" result = text.replace("World", "Python") print(result) # 输出: "Hello Python"
-
find()
和index()
: 查找子字符串的位置text = "Hello World" pos = text.find("World") # 返回 6 pos = text.index("World") # 返回 6,如果未找到则抛出异常
-
strip()
: 去除字符串首尾的空白字符(lstrip()
去除左侧空白,rstrip()
去除右侧空白)text = " Hello World " result = text.strip() # 输出: "Hello World"
-
upper()
和lower()
: 转换为全大写或全小写text = "Hello World" print(text.upper()) # 输出: "HELLO WORLD" print(text.lower()) # 输出: "hello world"
-
startswith()
和endswith()
: 判断字符串是否以特定前缀或后缀开头/结尾text = "Hello World" print(text.startswith("Hello")) # 输出: True print(text.endswith("World")) # 输出: True
5. 正则表达式操作
Python 的 re
模块提供了正则表达式功能。
-
匹配正则表达式:
re.match()
import re pattern = r"^Hello" text = "Hello World" match = re.match(pattern, text) if match: print("Match found") # 输出: "Match found"
-
搜索正则表达式:
re.search()
match = re.search(r"World$", text) if match: print("Match found") # 输出: "Match found"
-
替换:
re.sub()
result = re.sub(r"World", "Python", text) print(result) # 输出: "Hello Python"
-
查找所有:
re.findall()
text = "apple, banana, cherry" fruits = re.findall(r"\b\w+\b", text) print(fruits) # 输出: ['apple', 'banana', 'cherry']
-
编译正则表达式:
re.compile()
pattern = re.compile(r"^Hello") match = pattern.match(text) if match: print("Match found") # 输出: "Match found"
6. 其他常用字符串方法
-
capitalize()
: 将字符串的第一个字符转换为大写。text = "hello world" print(text.capitalize()) # 输出: "Hello world"
-
title()
: 将字符串的每个单词的首字母转换为大写。text = "hello world" print(text.title()) # 输出: "Hello World"
-
count()
: 返回子字符串在字符串中出现的次数。text = "banana" print(text.count("a")) # 输出: 3
-
isalnum()
: 判断字符串是否只包含字母和数字。text = "hello123" print(text.isalnum()) # 输出: True
-
isalpha()
: 判断字符串是否只包含字母。text = "hello" print(text.isalpha()) # 输出: True
-
isdigit()
: 判断字符串是否只包含数字。text = "12345" print(text.isdigit()) # 输出: True
-
isspace()
: 判断字符串是否只包含空白字符。text = " " print(text.isspace()) # 输出: True
总结
掌握 Python 中的字符串操作和正则表达式可以大大提高你的文本处理能力。了解如何切片、格式化、查找、替换字符串,并熟练使用正则表达式将使你在数据清洗、文本解析等任务中更加得心应手。