字符串是Python中最常用的数据类型之一,掌握字符串的各种操作方法对于Python编程至关重要。本文将全面介绍Python字符串操作的各个方面,从基础拼接和切片到高级格式化技巧。
一、字符串基础
1. 字符串创建
Python中字符串可以用单引号、双引号或三引号创建:
s1 = '单引号字符串'
s2 = "双引号字符串"
s3 = """多行
字符串"""
s4 = '''这也是
多行字符串'''
2. 转义字符
常用转义字符:
\n换行\t制表符\\反斜杠\'单引号\"双引号
print("这是第一行\n这是第二行")
print("路径: C:\\Users\\Name")
3. 原始字符串
在字符串前加r忽略转义:
path = r"C:\Users\Name\Documents"
print(path) # C:\Users\Name\Documents
二、字符串拼接
1. 使用+操作符
first_name = "张"
last_name = "三"
full_name = first_name + last_name
print(full_name) # 张三
2. 使用join()方法
适合拼接多个字符串:
words = ["Python", "是", "一门", "强大的", "语言"]
sentence = "".join(words)
print(sentence) # Python是一门强大的语言
# 用空格连接
print(" ".join(words)) # Python 是 一门 强大的 语言
3. 使用格式化方法
name = "李四"
age = 25
info = "姓名: {}, 年龄: {}".format(name, age)
print(info) # 姓名: 李四, 年龄: 25
三、字符串切片与索引
1. 基本索引
s = "Python编程"
print(s[0]) # P (第一个字符)
print(s[-1]) # 程 (最后一个字符)
2. 切片操作
语法:[start:end:step]
s = "Hello, World!"
print(s[0:5]) # Hello (索引0到4)
print(s[7:12]) # World
print(s[:5]) # Hello (从开始到索引4)
print(s[7:]) # World! (从索引7到末尾)
print(s[::2]) # Hlo ol! (每隔一个字符)
print(s[::-1]) # !dlroW ,olleH (反转字符串)
3. 字符串长度
s = "Python"
print(len(s)) # 6
四、字符串常用方法
1. 大小写转换
s = "Python Programming"
print(s.lower()) # python programming
print(s.upper()) # PYTHON PROGRAMMING
print(s.title()) # Python Programming
print(s.capitalize()) # Python programming
print(s.swapcase()) # pYTHON pROGRAMMING
2. 查找与替换
s = "Python是一门优秀的编程语言"
# 查找
print(s.find("优秀")) # 6 (返回索引)
print(s.find("Java")) # -1 (未找到)
print(s.index("编程")) # 9 (类似find但找不到会报错)
# 替换
print(s.replace("Python", "Java")) # Java是一门优秀的编程语言
3. 分割与连接
# 分割
csv = "苹果,香蕉,橙子,西瓜"
fruits = csv.split(",")
print(fruits) # ['苹果', '香蕉', '橙子', '西瓜']
# 多行分割
text = "第一行\n第二行\n第三行"
lines = text.splitlines()
print(lines) # ['第一行', '第二行', '第三行']
# 连接
print("-".join(fruits)) # 苹果-香蕉-橙子-西瓜
4. 去除空白
s = " 前后有空白 "
print(s.strip()) # "前后有空白"
print(s.lstrip()) # "前后有空白 "
print(s.rstrip()) # " 前后有空白"
5. 判断方法
num = "123"
alpha = "abc"
alnum = "abc123"
space = " \t\n"
print(num.isdigit()) # True
print(alpha.isalpha()) # True
print(alnum.isalnum()) # True
print(space.isspace()) # True
print(s.startswith("Py")) # True
print(s.endswith("语言")) # True
五、字符串格式化
1. %格式化 (旧式)
name = "王五"
age = 30
print("姓名: %s, 年龄: %d" % (name, age)) # 姓名: 王五, 年龄: 30
2. str.format()方法
print("姓名: {}, 年龄: {}".format(name, age))
print("姓名: {0}, 年龄: {1}, {0}今年{1}岁".format(name, age))
print("圆周率: {:.2f}".format(3.14159)) # 圆周率: 3.14
3. f-strings (Python 3.6+)
print(f"姓名: {name}, 年龄: {age}")
print(f"明年年龄: {age + 1}")
print(f"名字大写: {name.upper()}")
print(f"圆周率: {3.1415926:.3f}") # 圆周率: 3.142
六、字符串编码与解码
1. 编码
s = "中文"
utf8_bytes = s.encode("utf-8")
print(utf8_bytes) # b'\xe4\xb8\xad\xe6\x96\x87'
2. 解码
original = utf8_bytes.decode("utf-8")
print(original) # 中文
七、字符串高级操作
1. 字符串对齐
s = "Python"
print(s.ljust(10, "*")) # Python****
print(s.rjust(10, "*")) # ****Python
print(s.center(10, "*")) # **Python**
2. 字符串转换
# 字符串与列表转换
s = "a,b,c"
lst = s.split(",") # ['a', 'b', 'c']
s_new = ",".join(lst) # "a,b,c"
# 字符串与字典转换
from ast import literal_eval
s_dict = '{"name": "张三", "age": 25}'
d = literal_eval(s_dict) # {'name': '张三', 'age': 25}
3. 字符串模板
from string import Template
t = Template("姓名: $name, 年龄: $age")
print(t.substitute(name="赵六", age=40)) # 姓名: 赵六, 年龄: 40
八、性能考虑与最佳实践
1. 字符串拼接性能
- 少量字符串:
+操作符 - 大量字符串:
join()方法更高效
2. 字符串不变性
Python字符串是不可变的,每次"修改"都会创建新字符串:
s = "hello"
s += " world" # 创建了新字符串
3. 格式化选择
- Python 3.6+:优先使用f-strings
- 旧版本:使用str.format()
- 避免使用%格式化
九、实际应用示例
1. 密码强度检查
def check_password(password):
if len(password) < 8:
return "密码太短"
if not any(c.isupper() for c in password):
return "需要至少一个大写字母"
if not any(c.isdigit() for c in password):
return "需要至少一个数字"
return "密码强度足够"
2. 文本统计
text = "Python是一门流行的编程语言,Python简单易学。"
# 单词计数
words = text.split()
print(f"单词数: {len(words)}")
# 字符频率
from collections import defaultdict
freq = defaultdict(int)
for char in text:
freq[char] += 1
print("字符频率:", dict(freq))
3. 敏感信息过滤
def filter_sensitive(text, sensitive_words):
for word in sensitive_words:
text = text.replace(word, "*" * len(word))
return text
content = "这是一些包含敏感词的内容,如密码和账号"
filtered = filter_sensitive(content, ["敏感词", "密码", "账号"])
print(filtered) # 这是一些包含***的内容,如**和**
2万+

被折叠的 条评论
为什么被折叠?



