1. 什么是 Python 字符串?
在 Python 中,字符串(String)是一种不可变的序列数据类型,用于表示文本数据。字符串由一系列字符组成,可以包含字母、数字、符号和空格。
1.1 字符串的创建
Python 提供了多种创建字符串的方式:
python
# 使用单引号
str1 = 'Hello, World!'
# 使用双引号
str2 = "Python 字符串"
# 使用三引号(多行字符串)
str3 = '''这是一个
多行
字符串'''
str4 = """这也是一个
多行字符串"""
# 空字符串
empty_str = ""
2. 字符串的基本操作
2.1 字符串连接
python
# 使用 + 运算符
first_name = "张"
last_name = "三"
full_name = first_name + last_name # "张三"
# 使用 join() 方法
words = ["Python", "字符串", "教程"]
sentence = " ".join(words) # "Python 字符串 教程"
2.2 字符串重复
python
# 使用 * 运算符
line = "-" * 20 # "--------------------"
hello = "Hi" * 3 # "HiHiHi"
2.3 字符串长度
python
text = "Hello, Python!"
length = len(text) # 14
3. 字符串索引和切片
3.1 索引访问
python
text = "Python"
# 正向索引(从0开始)
print(text[0]) # 'P'
print(text[2]) # 't'
print(text[5]) # 'n'
# 负向索引(从-1开始)
print(text[-1]) # 'n'
print(text[-3]) # 'h'
3.2 切片操作
python
text = "Hello, Python!"
# 基本切片
print(text[0:5]) # "Hello"
print(text[7:13]) # "Python"
print(text[:5]) # "Hello"(从开头到索引4)
print(text[7:]) # "Python!"(从索引7到结尾)
# 带步长的切片
print(text[::2]) # "Hlo yhn"(每隔一个字符)
print(text[::-1]) # "!nohtyP ,olleH"(反转字符串)
4. 字符串常用方法
4.1 大小写转换
python
text = "Python String Tutorial"
print(text.lower()) # "python string tutorial"
print(text.upper()) # "PYTHON STRING TUTORIAL"
print(text.title()) # "Python String Tutorial"
print(text.capitalize()) # "Python string tutorial"
print(text.swapcase()) # "pYTHON sTRING tUTORIAL"
4.2 查找和替换
python
text = "Python is powerful. Python is easy to learn."
# 查找子串
print(text.find("Python")) # 0
print(text.find("Java")) # -1(未找到)
print(text.index("powerful")) # 12
print(text.count("Python")) # 2(出现次数)
# 替换子串
new_text = text.replace("Python", "Java")
print(new_text) # "Java is powerful. Java is easy to learn."
4.3 去除空白字符
python
text = " Python "
print(text.strip()) # "Python"
print(text.lstrip()) # "Python "
print(text.rstrip()) # " Python"
4.4 分割和连接
python
# 分割字符串
csv_data = "apple,banana,orange,grape"
fruits = csv_data.split(",") # ['apple', 'banana', 'orange', 'grape']
text = "one two three four"
words = text.split() # ['one', 'two', 'three', 'four']
# 按行分割
multi_line = "Line1\nLine2\nLine3"
lines = multi_line.splitlines() # ['Line1', 'Line2', 'Line3']
# 连接字符串
joined = "-".join(words) # "one-two-three-four"
5. 字符串格式化
5.1 传统格式化(% 操作符)
python
name = "张三"
age = 25
score = 95.5
# 基本格式化
print("姓名:%s,年龄:%d" % (name, age))
print("分数:%.2f" % score) # 保留两位小数
5.2 format() 方法
python
name = "李四"
age = 30
# 位置参数
print("姓名:{},年龄:{}".format(name, age))
# 关键字参数
print("姓名:{name},年龄:{age}".format(name=name, age=age))
# 格式化数字
pi = 3.1415926
print("圆周率:{:.2f}".format(pi)) # "圆周率:3.14"
5.3 f-string(Python 3.6+)
python
name = "王五"
age = 28
height = 1.75
# 基本使用
print(f"姓名:{name},年龄:{age}")
# 表达式计算
print(f"明年年龄:{age + 1}")
# 格式化数字
print(f"身高:{height:.2f}米") # "身高:1.75米"
# 调用方法
text = "hello world"
print(f"大写:{text.upper()}") # "大写:HELLO WORLD"
6. 字符串检查方法
python
text1 = "Python123"
text2 = "12345"
text3 = "HELLO"
text4 = "hello"
text5 = "Python Tutorial"
text6 = " "
text7 = ""
print(text1.isalnum()) # True(字母或数字)
print(text1.isalpha()) # False(不全是字母)
print(text2.isdigit()) # True(全是数字)
print(text3.isupper()) # True(全大写)
print(text4.islower()) # True(全小写)
print(text5.istitle()) # True(每个单词首字母大写)
print(text6.isspace()) # True(全是空白字符)
print(text7.isascii()) # True(ASCII字符)
7. 转义字符和原始字符串
7.1 常用转义字符
python
print("换行:第一行\n第二行")
print("制表符:姓名\t年龄")
print("双引号:\"Python\"")
print("单引号:\'字符串\'")
print("反斜杠:\\")
print("Unicode:\u4e2d\u6587") # "中文"
7.2 原始字符串(Raw String)
python
# 普通字符串中的反斜杠需要转义
path1 = "C:\\Users\\Documents\\file.txt"
# 原始字符串(r前缀)
path2 = r"C:\Users\Documents\file.txt"
print(path1) # "C:\Users\Documents\file.txt"
print(path2) # "C:\Users\Documents\file.txt"
8. 字符串编码和解码
8.1 编码(字符串 → 字节)
python
text = "你好,世界!"
# UTF-8 编码(最常用)
utf8_bytes = text.encode("utf-8")
print(utf8_bytes) # b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
# GBK 编码(中文Windows常用)
gbk_bytes = text.encode("gbk")
8.2 解码(字节 → 字符串)
python
# 从 UTF-8 字节解码
decoded_text = utf8_bytes.decode("utf-8")
print(decoded_text) # "你好,世界!"
# 从 GBK 字节解码
decoded_gbk = gbk_bytes.decode("gbk")
9. 字符串性能优化技巧
9.1 使用 join() 代替 + 连接大量字符串
python
# 不推荐(性能差)
result = ""
for i in range(10000):
result += str(i)
# 推荐(性能好)
parts = []
for i in range(10000):
parts.append(str(i))
result = "".join(parts)
9.2 使用 in 运算符检查子串
python
text = "Python programming is fun"
# 推荐
if "Python" in text:
print("包含Python")
# 不推荐
if text.find("Python") != -1:
print("包含Python")
10. 实际应用示例
10.1 数据清洗
python
def clean_string(text):
"""清洗字符串:去除多余空格,首字母大写"""
# 去除首尾空格
text = text.strip()
# 将多个连续空格替换为单个空格
text = " ".join(text.split())
# 首字母大写
return text.capitalize()
dirty_text = " python 字符串 教程 "
clean_text = clean_string(dirty_text)
print(clean_text) # "Python 字符串 教程"
10.2 密码强度检查
python
def check_password_strength(password):
"""检查密码强度"""
if len(password) < 8:
return "密码太短,至少需要8个字符"
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = any(not c.isalnum() for c in password)
score = sum([has_upper, has_lower, has_digit, has_special])
if score == 4:
return "密码强度:强"
elif score >= 2:
return "密码强度:中"
else:
return "密码强度:弱"
print(check_password_strength("Abc123!@#")) # "密码强度:强"
10.3 提取文件扩展名
python
def get_file_extension(filename):
"""获取文件扩展名"""
if "." not in filename:
return ""
# 分割文件名和扩展名
parts = filename.rsplit(".", 1)
return parts[1].lower() if len(parts) > 1 else ""
print(get_file_extension("document.pdf")) # "pdf"
print(get_file_extension("image.JPEG")) # "jpeg"
print(get_file_extension("no_extension")) # ""
总结
Python 字符串是编程中最常用的数据类型之一,掌握字符串的各种操作对于编写高效、清晰的代码至关重要。本文涵盖了从基础创建、索引切片到高级格式化、编码解码的全面内容。记住以下要点:
- 字符串不可变:所有修改操作都会返回新字符串
- 优先使用 f-string:Python 3.6+ 中最简洁高效的格式化方式
- 大量连接用 join():避免使用 + 连接大量字符串
- 注意编码问题:处理中文等非ASCII字符时明确指定编码
通过不断练习这些字符串操作,您将能够更高效地处理文本数据,编写出更优雅的 Python 代码。