Skip to content

字符串

字符串是Python中最常用的数据类型之一。字符串是由字符组成的序列,用于表示文本信息。Python中的字符串是不可变的,这意味着一旦创建就不能修改。本章将详细介绍字符串的创建、操作和常用方法。

字符串的创建

基本创建方式

python
# 创建字符串的多种方式

# 1. 使用单引号
str1 = 'Hello, Python!'
print(f"单引号字符串: {str1}")

# 2. 使用双引号
str2 = "Hello, Python!"
print(f"双引号字符串: {str2}")

# 3. 单引号和双引号可以互相嵌套
str3 = "他说:'Python很有趣'"
str4 = '他说:"Python很有趣"'
print(f"双引号嵌套单引号: {str3}")
print(f"单引号嵌套双引号: {str4}")

# 4. 使用三引号创建多行字符串
str5 = '''这是第一行
这是第二行
这是第三行'''
print(f"多行字符串:\n{str5}")

str6 = """这也是
多行字符串"""
print(f"双引号多行字符串:\n{str6}")

# 5. 创建空字符串
empty_str1 = ''
empty_str2 = ""
empty_str3 = str()
print(f"空字符串1: '{empty_str1}', 长度: {len(empty_str1)}")
print(f"空字符串2: '{empty_str2}', 长度: {len(empty_str2)}")
print(f"空字符串3: '{empty_str3}', 长度: {len(empty_str3)}")

转义字符

python
# 转义字符的使用

# \n - 换行
print("第一行\n第二行")

# \t - 制表符(Tab)
print("姓名\t年龄\t城市")
print("张三\t20\t北京")

# \\ - 反斜杠
print("文件路径: C:\\Users\\Documents")

# \' - 单引号
print('It\'s a beautiful day!')

# \" - 双引号
print("He said, \"Hello!\"")

# \r - 回车(光标移到行首)
print("Hello\rWorld")  # 输出: World(Hello被覆盖)

# \b - 退格
print("Hello\b World")  # 输出: Hell World

# \ooo - 八进制表示的字符
print("\101\102\103")  # 输出: ABC

# \xhh - 十六进制表示的字符
print("\x41\x42\x43")  # 输出: ABC

# 常用转义字符汇总表
print("""
常用转义字符:
\\n  - 换行
\\t  - 制表符
\\\\  - 反斜杠
\\'  - 单引号
\\"  - 双引号
\\r  - 回车
\\b  - 退格
""")

原始字符串

python
# 原始字符串(Raw String)

# 普通字符串中的反斜杠会被解释为转义字符
normal_path = "C:\\Users\\Documents\\file.txt"
print(f"普通字符串: {normal_path}")

# 原始字符串以 r 开头,不处理转义字符
raw_path = r"C:\Users\Documents\file.txt"
print(f"原始字符串: {raw_path}")

# 原始字符串在正则表达式中非常有用
import re

# 不使用原始字符串,需要双重转义
pattern1 = "\\d+\\.\\d+"

# 使用原始字符串更清晰
pattern2 = r"\d+\.\d+"

text = "价格: 99.99元"
result = re.search(pattern2, text)
print(f"匹配结果: {result.group()}")  # 输出: 99.99

# 原始字符串不能以奇数个反斜杠结尾
# raw_str = r"\"  # SyntaxError
raw_str = r"\\"   # 正确
print(f"两个反斜杠: {raw_str}")

字符串的访问

索引访问

python
# 字符串索引访问

text = "Python"

# 正向索引(从0开始)
print(f"第一个字符: {text[0]}")   # P
print(f"第二个字符: {text[1]}")   # y
print(f"最后一个字符: {text[5]}") # n

# 负向索引(从-1开始,从末尾计数)
print(f"最后一个字符: {text[-1]}")   # n
print(f"倒数第二个字符: {text[-2]}") # o
print(f"第一个字符: {text[-6]}")     # P

# 索引越界会报错
# print(text[10])  # IndexError: string index out of range

# 遍历字符串
print("\n=== 遍历字符串 ===")
for char in text:
    print(char, end=" ")
print()

# 带索引遍历
print("\n=== 带索引遍历 ===")
for index, char in enumerate(text):
    print(f"索引{index}: {char}")

切片操作

python
# 字符串切片

text = "Hello, Python!"

# 基本语法: str[start:end:step]
# start: 起始索引(包含,默认0)
# end: 结束索引(不包含,默认到末尾)
# step: 步长(默认1)

# 1. 基本切片
print(f"原字符串: {text}")
print(f"[0:5]: {text[0:5]}")      # Hello
print(f"[7:13]: {text[7:13]}")    # Python
print(f"[:5]: {text[:5]}")        # Hello(省略start)
print(f"[7:]: {text[7:]}")        # Python!(省略end)
print(f"[:]: {text[:]}")          # Hello, Python!(复制整个字符串)

# 2. 负索引切片
print(f"[-7:-1]: {text[-7:-1]}")  # Python
print(f"[-7:]: {text[-7:]}")      # Python!
print(f"[:-8]: {text[:-8]}")      # Hello,

# 3. 步长切片
print(f"[::2]: {text[::2]}")      # Hlo yhn(每隔一个字符)
print(f"[::3]: {text[::3]}")      # HlPh(每隔两个字符)

# 4. 反向切片
print(f"[::-1]: {text[::-1]}")    # !nohtyP ,olleH(反转字符串)
print(f"[13:7:-1]: {text[13:7:-1]}")  # !nohtyP(反向切片)

# 5. 实用切片示例
# 获取文件扩展名
filename = "document.pdf"
ext = filename[filename.rfind(".") + 1:]
print(f"文件扩展名: {ext}")

# 隐藏手机号中间四位
phone = "13812345678"
hidden = phone[:3] + "****" + phone[7:]
print(f"隐藏后手机号: {hidden}")

# 截取域名
url = "https://www.example.com/page"
domain = url.split("/")[2]
print(f"域名: {domain}")

字符串运算

python
# 字符串运算

# 1. 字符串拼接
str1 = "Hello"
str2 = "Python"

# 使用 + 运算符
result = str1 + ", " + str2 + "!"
print(f"拼接结果: {result}")

# 使用 += 运算符
greeting = "你好"
greeting += ","
greeting += "世界"
print(f"+=结果: {greeting}")

# 2. 字符串重复
repeat_str = "Python " * 3
print(f"重复3次: {repeat_str}")

# 打印分隔线
separator = "-" * 30
print(separator)

# 3. 字符串比较
str_a = "apple"
str_b = "banana"
str_c = "apple"

print(f"str_a == str_c: {str_a == str_c}")  # True(内容相等)
print(f"str_a != str_b: {str_a != str_b}")  # True(内容不等)

# 比较大小(按字典序)
print(f"'apple' < 'banana': {'apple' < 'banana'}")  # True
print(f"'apple' > 'Apple': {'apple' > 'Apple'}")    # True(小写字母大于大写)

# 4. 成员运算
text = "Hello, Python!"
print(f"'Python' in text: {'Python' in text}")      # True
print(f"'python' in text: {'python' in text}")      # False(区分大小写)
print(f"'Java' not in text: {'Java' not in text}")  # True

# 5. 获取字符串长度
print(f"字符串长度: {len(text)}")

字符串格式化

使用 % 格式化(旧式)

python
# % 格式化(旧式格式化)

name = "张三"
age = 20
score = 95.5

# 基本格式化
print("姓名: %s" % name)           # 字符串
print("年龄: %d岁" % age)          # 整数
print("成绩: %.1f分" % score)      # 浮点数(保留1位小数)

# 常用格式化符号
"""
%s - 字符串
%d - 整数
%f - 浮点数
%.nf - 保留n位小数的浮点数
%x - 十六进制整数
%o - 八进制整数
%e - 科学计数法
%% - 百分号本身
"""

# 多个值格式化
print("姓名: %s, 年龄: %d岁, 成绩: %.1f分" % (name, age, score))

# 使用字典格式化
student = {"name": "李四", "age": 22, "score": 88.5}
print("姓名: %(name)s, 年龄: %(age)d岁, 成绩: %(score).1f分" % student)

# 宽度和对齐
print("|%10s|" % "hello")   # 右对齐,宽度10
print("|%-10s|" % "hello")  # 左对齐,宽度10
print("|%10d|" % 123)       # 数字右对齐
print("|%010d|" % 123)      # 用0填充

使用 str.format() 方法

python
# str.format() 格式化

name = "张三"
age = 20
score = 95.5

# 1. 位置参数
print("姓名: {}, 年龄: {}岁".format(name, age))
print("姓名: {0}, 年龄: {1}岁, 重复: {0}".format(name, age))

# 2. 关键字参数
print("姓名: {name}, 年龄: {age}岁".format(name="李四", age=22))

# 3. 混合使用
print("姓名: {0}, 年龄: {age}岁, 成绩: {1}".format(name, score, age=age))

# 4. 访问属性和索引
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("王五", 25)
print("姓名: {0.name}, 年龄: {0.age}".format(person))

# 访问列表/元组元素
scores = [90, 85, 92]
print("第一科: {0[0]}, 第二科: {0[1]}".format(scores))

# 5. 格式规范
# 宽度和对齐
print("|{:10}|".format("hello"))    # 左对齐
print("|{:>10}|".format("hello"))   # 右对齐
print("|{:^10}|".format("hello"))   # 居中

# 数字格式化
print("{:.2f}".format(3.14159))     # 保留2位小数
print("{:+.2f}".format(3.14))       # 显示正号
print("{:,.2f}".format(1234567.89)) # 千分位分隔

# 进制转换
print("{:b}".format(10))    # 二进制
print("{:o}".format(10))    # 八进制
print("{:x}".format(10))    # 十六进制(小写)
print("{:X}".format(10))    # 十六进制(大写)

# 百分比
print("{:.1%}".format(0.856))  # 85.6%

使用 f-string(推荐)

python
# f-string 格式化(Python 3.6+,推荐使用)

name = "张三"
age = 20
score = 95.5

# 1. 基本用法
print(f"姓名: {name}, 年龄: {age}岁")

# 2. 表达式计算
print(f"明年年龄: {age + 1}岁")
print(f"成绩翻倍: {score * 2}分")
print(f"是否成年: {'是' if age >= 18 else '否'}")

# 3. 调用函数和方法
print(f"姓名大写: {name.upper()}")
print(f"姓名长度: {len(name)}")
print(f"平方根: {pow(16, 0.5)}")

# 4. 格式规范
# 宽度和对齐
print(f"|{name:<10}|")   # 左对齐
print(f"|{name:>10}|")   # 右对齐
print(f"|{name:^10}|")   # 居中

# 数字格式化
pi = 3.14159265
print(f"保留2位小数: {pi:.2f}")
print(f"科学计数法: {pi:.2e}")
print(f"百分比: {0.856:.1%}")

# 千分位分隔
big_number = 1234567890
print(f"千分位: {big_number:,}")
print(f"千分位+小数: {1234567.89:,.2f}")

# 进制转换
num = 255
print(f"十进制: {num:d}")
print(f"二进制: {num:b}")
print(f"八进制: {num:o}")
print(f"十六进制: {num:x}")
print(f"十六进制(大写): {num:X}")

# 5. 嵌套引号
print(f"他说: '{name}你好'")

# 6. 多行 f-string
info = f"""
学生信息:
  姓名: {name}
  年龄: {age}
  成绩: {score}
"""
print(info)

# 7. f-string 中使用字典
student = {"name": "李四", "age": 22}
print(f"姓名: {student['name']}, 年龄: {student['age']}")

# 8. 调试模式(Python 3.8+)
# 使用 = 可以同时显示变量名和值
x = 10
y = 20
print(f"{x=}, {y=}")           # 输出: x=10, y=20
print(f"{x + y=}")             # 输出: x + y=30
print(f"{name=}, {age=}")      # 输出: name='张三', age=20

字符串常用方法

大小写转换

python
# 大小写转换方法

text = "Hello, Python World!"

# 1. 转换为小写
print(f"lower(): {text.lower()}")       # hello, python world!

# 2. 转换为大写
print(f"upper(): {text.upper()}")       # HELLO, PYTHON WORLD!

# 3. 首字母大写
print(f"capitalize(): {text.capitalize()}")  # Hello, python world!

# 4. 每个单词首字母大写
print(f"title(): {text.title()}")       # Hello, Python World!

# 5. 大小写互换
print(f"swapcase(): {text.swapcase()}") # hELLO, pYTHON wORLD!

# 6. 判断大小写
print(f"islower(): {'hello'.islower()}")   # True
print(f"isupper(): {'HELLO'.isupper()}")   # True
print(f"istitle(): {'Hello World'.istitle()}")  # True

# 实际应用:不区分大小写的比较
user_input = "PYTHON"
if user_input.lower() == "python":
    print("输入正确!")

查找与替换

python
# 查找与替换方法

text = "Hello, Python! Python is great!"

# 1. find() - 查找子串位置(从左开始)
pos = text.find("Python")
print(f"find('Python'): {pos}")         # 7

# 未找到返回 -1
pos = text.find("Java")
print(f"find('Java'): {pos}")           # -1

# 指定查找范围
pos = text.find("Python", 10)           # 从索引10开始查找
print(f"find('Python', 10): {pos}")     # 15

# 2. rfind() - 从右开始查找
pos = text.rfind("Python")
print(f"rfind('Python'): {pos}")        # 15

# 3. index() - 类似find(),但未找到会报错
pos = text.index("Python")
print(f"index('Python'): {pos}")        # 7

# pos = text.index("Java")  # ValueError

# 4. rindex() - 从右开始查找
pos = text.rindex("Python")
print(f"rindex('Python'): {pos}")       # 15

# 5. count() - 统计子串出现次数
count = text.count("Python")
print(f"count('Python'): {count}")      # 2

# 6. replace() - 替换子串
new_text = text.replace("Python", "Java")
print(f"replace('Python', 'Java'): {new_text}")

# 指定替换次数
new_text = text.replace("Python", "Java", 1)
print(f"replace(..., 1): {new_text}")   # 只替换第一个

# 实际应用:敏感词过滤
comment = "这是一条包含敏感词的评论"
filtered = comment.replace("敏感词", "***")
print(f"过滤后: {filtered}")

分割与连接

python
# 分割与连接方法

# 1. split() - 分割字符串
text = "apple,banana,orange,grape"
fruits = text.split(",")
print(f"split(','): {fruits}")  # ['apple', 'banana', 'orange', 'grape']

# 限制分割次数
fruits = text.split(",", 2)
print(f"split(',', 2): {fruits}")  # ['apple', 'banana', 'orange,grape']

# 2. splitlines() - 按行分割
multiline = "第一行\n第二行\n第三行"
lines = multiline.splitlines()
print(f"splitlines(): {lines}")

# 3. partition() - 分割成三部分
text = "hello@world.com"
before, sep, after = text.partition("@")
print(f"partition('@'): '{before}', '{sep}', '{after}'")

# 未找到分隔符
before, sep, after = text.partition("#")
print(f"partition('#'): '{before}', '{sep}', '{after}'")

# 4. rpartition() - 从右边开始分割
path = "/home/user/documents/file.txt"
before, sep, after = path.rpartition("/")
print(f"rpartition('/'): '{before}', '{sep}', '{after}'")

# 5. join() - 连接字符串列表
words = ["Hello", "Python", "World"]
result = " ".join(words)
print(f"join(' '): {result}")  # Hello Python World

result = "-".join(words)
print(f"join('-'): {result}")  # Hello-Python-World

result = "".join(words)
print(f"join(''): {result}")   # HelloPythonWorld

# 实际应用:路径拼接
import os
path = os.path.join("home", "user", "documents")
print(f"路径: {path}")

# 实际应用:URL拼接
url = "/".join(["https:", "", "example.com", "api", "users"])
print(f"URL: {url}")

去除空白字符

python
# 去除空白字符方法

text = "   Hello, Python!   "

# 1. strip() - 去除两端空白
print(f"strip(): '{text.strip()}'")

# 2. lstrip() - 去除左侧空白
print(f"lstrip(): '{text.lstrip()}'")

# 3. rstrip() - 去除右侧空白
print(f"rstrip(): '{text.rstrip()}'")

# 4. 去除指定字符
text2 = "###Hello, Python!###"
print(f"strip('#'): '{text2.strip('#')}'")

# 去除多种字符
text3 = "xxyyHello, Python!yyxx"
print(f"strip('xy'): '{text3.strip('xy')}'")

# 实际应用:清理用户输入
user_input = "  张三  "
clean_name = user_input.strip()
print(f"清理后: '{clean_name}'")

# 实际应用:解析数据行
csv_line = "  张三, 20, 北京  "
fields = [field.strip() for field in csv_line.split(",")]
print(f"字段: {fields}")

判断方法

python
# 字符串判断方法

# 1. 判断是否以指定字符串开头/结尾
filename = "document.pdf"
print(f"startswith('doc'): {filename.startswith('doc')}")  # True
print(f"endswith('.pdf'): {filename.endswith('.pdf')}")    # True

# 检查多种后缀
print(f"endswith(图片): {filename.endswith(('.jpg', '.png', '.gif'))}")

# 2. 判断字符串内容类型
print(f"'12345'.isdigit(): {'12345'.isdigit()}")      # True(只含数字)
print(f"'123.45'.isdigit(): {'123.45'.isdigit()}")    # False

print(f"'hello'.isalpha(): {'hello'.isalpha()}")      # True(只含字母)
print(f"'hello123'.isalpha(): {'hello123'.isalpha()}")# False

print(f"'hello123'.isalnum(): {'hello123'.isalnum()}")# True(字母或数字)

print(f"'   '.isspace(): {'   '.isspace()}")          # True(只含空白)

# 3. 判断是否为有效标识符
print(f"'my_var'.isidentifier(): {'my_var'.isidentifier()}")  # True
print(f"'123var'.isidentifier(): {'123var'.isidentifier()}")  # False

# 4. 判断是否为数字的各种形式
print(f"'123'.isnumeric(): {'123'.isnumeric()}")      # True
print(f"'一二三'.isnumeric(): {'一二三'.isnumeric()}")  # True(中文数字)
print(f"'①②③'.isnumeric(): {'①②③'.isnumeric()}")     # True

print(f"'123'.isdecimal(): {'123'.isdecimal()}")      # True
print(f"'123.45'.isdecimal(): {'123.45'.isdecimal()}")# False

# 实际应用:验证输入
def validate_username(username):
    if not username.isalnum():
        return "用户名只能包含字母和数字"
    if not username[0].isalpha():
        return "用户名必须以字母开头"
    if len(username) < 3:
        return "用户名至少3个字符"
    return "用户名有效"

print(validate_username("user123"))   # 用户名有效
print(validate_username("123user"))   # 用户名必须以字母开头
print(validate_username("user@123"))  # 用户名只能包含字母和数字

对齐与填充

python
# 字符串对齐与填充方法

text = "Python"

# 1. center() - 居中对齐
print(f"center(20): '{text.center(20)}'")
print(f"center(20, '*'): '{text.center(20, '*')}'")

# 2. ljust() - 左对齐
print(f"ljust(20): '{text.ljust(20)}'")
print(f"ljust(20, '-'): '{text.ljust(20, '-')}'")

# 3. rjust() - 右对齐
print(f"rjust(20): '{text.rjust(20)}'")
print(f"rjust(20, '-'): '{text.rjust(20, '-')}'")

# 4. zfill() - 用0填充(常用于数字)
num = "42"
print(f"zfill(5): '{num.zfill(5)}'")  # 00042

# 负数处理
num = "-42"
print(f"zfill(5): '{num.zfill(5)}'")  # -0042

# 实际应用:格式化输出表格
data = [
    ("张三", 90, "优秀"),
    ("李四", 85, "良好"),
    ("王五", 78, "中等"),
]

print("\n成绩单:")
print("-" * 40)
print(f"{'姓名'.center(10)}{'成绩'.center(10)}{'等级'.center(10)}")
print("-" * 40)
for name, score, grade in data:
    print(f"{name.center(10)}{str(score).center(10)}{grade.center(10)}")
print("-" * 40)

# 实际应用:显示进度条
def show_progress(current, total, width=50):
    percent = current / total
    filled = int(width * percent)
    bar = "█" * filled + "░" * (width - filled)
    print(f"\r[{bar}] {percent:.1%}", end="")

import time
print("\n进度演示:")
for i in range(101):
    show_progress(i, 100)
    time.sleep(0.02)
print()  # 换行

编码与解码

python
# 字符串编码与解码

text = "你好,Python!"

# 1. 编码(字符串 -> 字节)
# UTF-8 编码
utf8_bytes = text.encode("utf-8")
print(f"UTF-8编码: {utf8_bytes}")

# GBK 编码
gbk_bytes = text.encode("gbk")
print(f"GBK编码: {gbk_bytes}")

# 使用 errors 参数处理编码错误
text_with_error = "hello你好€€€"  # € 符号在 GBK 中不存在
# gbk_bytes = text_with_error.encode("gbk")  # UnicodeEncodeError

# 忽略无法编码的字符
gbk_bytes = text_with_error.encode("gbk", errors="ignore")
print(f"忽略错误: {gbk_bytes}")

# 替换无法编码的字符
gbk_bytes = text_with_error.encode("gbk", errors="replace")
print(f"替换错误: {gbk_bytes}")

# 2. 解码(字节 -> 字符串)
# 从 UTF-8 解码
decoded = utf8_bytes.decode("utf-8")
print(f"UTF-8解码: {decoded}")

# 从 GBK 解码
decoded = gbk_bytes.decode("gbk")
print(f"GBK解码: {decoded}")

# 3. 获取字节长度
print(f"字符串长度: {len(text)}")
print(f"UTF-8字节长度: {len(utf8_bytes)}")
print(f"GBK字节长度: {len(gbk_bytes)}")

# 实际应用:文件编码处理
# 写入文件时指定编码
content = "这是中文内容"
with open("test.txt", "w", encoding="utf-8") as f:
    f.write(content)

# 读取文件时指定编码
with open("test.txt", "r", encoding="utf-8") as f:
    content = f.read()
print(f"文件内容: {content}")

# 清理测试文件
import os
os.remove("test.txt")

字符串其他操作

字符串反转

python
# 字符串反转的多种方法

text = "Python"

# 方法1:使用切片(推荐)
reversed_text = text[::-1]
print(f"切片反转: {reversed_text}")

# 方法2:使用 reversed() 函数
reversed_text = "".join(reversed(text))
print(f"reversed(): {reversed_text}")

# 方法3:使用循环
reversed_text = ""
for char in text:
    reversed_text = char + reversed_text
print(f"循环反转: {reversed_text}")

# 方法4:使用列表
char_list = list(text)
char_list.reverse()
reversed_text = "".join(char_list)
print(f"列表反转: {reversed_text}")

# 判断回文字符串
def is_palindrome(s):
    # 去除空格和标点,转小写
    s = "".join(c.lower() for c in s if c.isalnum())
    return s == s[::-1]

print(f"'上海自来水来自海上' 是回文: {is_palindrome('上海自来水来自海上')}")
print(f"'A man a plan a canal Panama' 是回文: {is_palindrome('A man a plan a canal Panama')}")

字符串排序

python
# 字符串排序

text = "python"

# 1. 按字符排序
sorted_chars = sorted(text)
print(f"排序后字符列表: {sorted_chars}")

# 排序后连接成字符串
sorted_text = "".join(sorted_chars)
print(f"排序后字符串: {sorted_text}")

# 2. 反向排序
sorted_text = "".join(sorted(text, reverse=True))
print(f"反向排序: {sorted_text}")

# 3. 按单词排序
sentence = "python is a great programming language"
words = sentence.split()
words.sort()
print(f"单词排序: {words}")

# 按单词长度排序
words_by_length = sorted(sentence.split(), key=len)
print(f"按长度排序: {words_by_length}")

# 按单词长度降序
words_by_length_desc = sorted(sentence.split(), key=len, reverse=True)
print(f"按长度降序: {words_by_length_desc}")

字符串与列表转换

python
# 字符串与列表的相互转换

# 1. 字符串转列表
text = "Python"
char_list = list(text)
print(f"字符串转列表: {char_list}")

# 2. 列表转字符串
words = ["Hello", "Python", "World"]
sentence = " ".join(words)
print(f"列表转字符串: {sentence}")

# 3. 字符串转ASCII码列表
text = "ABC"
ascii_list = [ord(c) for c in text]
print(f"ASCII码列表: {ascii_list}")

# 4. ASCII码列表转字符串
ascii_list = [65, 66, 67]
text = "".join(chr(code) for code in ascii_list)
print(f"ASCII转字符串: {text}")

# 5. 字符串与字节转换
text = "Hello"
# 字符串 -> 字节
bytes_data = text.encode()
print(f"字节: {bytes_data}")

# 字节 -> 字符串
text = bytes_data.decode()
print(f"字符串: {text}")

实用字符串处理示例

文本清洗

python
# 文本清洗示例

def clean_text(text):
    """清洗文本:去除多余空白、标点等"""
    import re
    
    # 去除首尾空白
    text = text.strip()
    
    # 将多个空白字符替换为单个空格
    text = re.sub(r'\s+', ' ', text)
    
    # 去除特殊字符(保留中文、英文、数字)
    text = re.sub(r'[^\w\s\u4e00-\u9fff]', '', text)
    
    return text

dirty_text = "  Hello,   世界!  这是一个  测试...  "
clean = clean_text(dirty_text)
print(f"清洗前: '{dirty_text}'")
print(f"清洗后: '{clean}'")

密码强度检测

python
# 密码强度检测

def check_password_strength(password):
    """检测密码强度"""
    score = 0
    feedback = []
    
    # 检查长度
    if len(password) >= 8:
        score += 1
    else:
        feedback.append("密码长度至少8位")
    
    # 检查是否包含数字
    if any(c.isdigit() for c in password):
        score += 1
    else:
        feedback.append("应包含数字")
    
    # 检查是否包含小写字母
    if any(c.islower() for c in password):
        score += 1
    else:
        feedback.append("应包含小写字母")
    
    # 检查是否包含大写字母
    if any(c.isupper() for c in password):
        score += 1
    else:
        feedback.append("应包含大写字母")
    
    # 检查是否包含特殊字符
    special_chars = "!@#$%^&*()_+-=[]{}|;:',.<>?"
    if any(c in special_chars for c in password):
        score += 1
    else:
        feedback.append("应包含特殊字符")
    
    # 评定强度
    if score <= 2:
        strength = "弱"
    elif score <= 3:
        strength = "中等"
    elif score <= 4:
        strength = "强"
    else:
        strength = "非常强"
    
    return strength, feedback

# 测试
passwords = ["123456", "password", "Password123", "P@ssw0rd!"]
for pwd in passwords:
    strength, feedback = check_password_strength(pwd)
    print(f"密码: {pwd}")
    print(f"  强度: {strength}")
    if feedback:
        print(f"  建议: {', '.join(feedback)}")
    print()

文本统计

python
# 文本统计

def text_statistics(text):
    """统计文本信息"""
    # 基本统计
    char_count = len(text)
    char_count_no_space = len(text.replace(" ", ""))
    word_count = len(text.split())
    line_count = len(text.splitlines()) or 1
    
    # 字符频率统计
    from collections import Counter
    char_freq = Counter(text.lower())
    
    # 统计字母、数字、其他字符
    letters = sum(c.isalpha() for c in text)
    digits = sum(c.isdigit() for c in text)
    spaces = sum(c.isspace() for c in text)
    others = char_count - letters - digits - spaces
    
    print("=== 文本统计 ===")
    print(f"总字符数: {char_count}")
    print(f"字符数(不含空格): {char_count_no_space}")
    print(f"单词数: {word_count}")
    print(f"行数: {line_count}")
    print(f"字母数: {letters}")
    print(f"数字数: {digits}")
    print(f"空格数: {spaces}")
    print(f"其他字符数: {others}")
    print(f"\n最常见的5个字符:")
    for char, count in char_freq.most_common(5):
        if char != ' ':
            print(f"  '{char}': {count}次")

# 测试
sample_text = """
Python是一种广泛使用的编程语言。
它由Guido van Rossum于1991年创建。
Python具有简洁、易读的语法特点。
"""
text_statistics(sample_text)

小结

本章学习了Python字符串的详细用法:

字符串创建

  • 单引号、双引号、三引号
  • 转义字符和原始字符串

字符串访问

  • 索引访问(正向和负向)
  • 切片操作

字符串格式化

  • % 格式化(旧式)
  • str.format() 方法
  • f-string(推荐)

常用方法

  • 大小写转换:lower(), upper(), title()
  • 查找替换:find(), replace(), count()
  • 分割连接:split(), join(), partition()
  • 去除空白:strip(), lstrip(), rstrip()
  • 判断方法:startswith(), isdigit(), isalpha()
  • 对齐填充:center(), ljust(), rjust(), zfill()

掌握字符串操作是Python编程的基础,在实际开发中会频繁使用这些方法来处理文本数据。