从三引号文档注释到切片逆序,python 字符串的命门全在这了!
一、三引号的三种用途
1.1 文档注释(模块级 docstring)
文件开头用三引号注释整个 .py 文件的用途,help() 和 ide 都能读取:
""" 数据分析工具模块 功能:数据清洗、统计计算、可视化导出 作者:张三 日期:2026-07-15 """ import pandas as pd import numpy as np # 你的代码从这里开始...
1.2 函数注释(函数 docstring)
函数定义下一行,三引号写函数说明、参数、返回值。调用 help(func) 即可查看:
def calculate_average(nums):
"""
计算列表的平均值
args:
nums: 数字列表
returns:
float: 平均值
"""
if not nums:
return 0.0
return sum(nums) / len(nums)
# 查看文档
print(help(calculate_average))
# 输出:
# calculate_average(nums)
# 计算列表的平均值
# args:
# nums: 数字列表
# returns:
# float: 平均值
1.3 类注释
类的三引号注释写类的用途、属性和示例用法:
class student:
"""
学生类,管理学生信息和成绩
attributes:
name: 学生姓名
score: 成绩字典,如 {'math': 90, 'english': 85}
example:
>>> s = student("小明", {'math': 95, 'english': 88})
>>> s.get_average()
91.5
"""
def __init__(self, name, score):
self.name = name
self.score = score
def get_average(self):
return sum(self.score.values()) / len(self.score)
二、字符串声明与转义字符
2.1 三种声明方式
s1 = 'hello' # 单引号 s2 = "world" # 双引号 s3 = '''多行 字符串''' # 三引号(保留换行) s4 = """也是 多行""" # 三双引号 # 含有引号的字符串——用不同引号声明避免冲突 s5 = "i'm a developer" # 内含单引号,外层用双引号 s6 = '他说:"你好"' # 内含双引号,外层用单引号 print(s3) # 输出两行
2.2 转义字符表
| 转义字符 | 含义 | 示例 | 输出 |
|---|---|---|---|
\' | 单引号 | 'it\'s ok' | it’s ok |
\" | 双引号 | "他说:\"你好\"" | 他说:“你好” |
\' ' \ | 三引号内的引号 | '''don\'t''' | don’t |
\n | 换行 | '第一行\n第二行' | 两行 |
\t | 制表符缩进 | '姓名\t年龄' | 姓名年龄 |
\\ | 反斜杠本身 | '路径:c:\\users' | 路径:c:\users |
# 实战示例 path = "c:\\users\\administrator\\documents" print(path) # c:\users\administrator\documents info = "姓名:张三\n年龄:25\n城市:上海" print(info) # 姓名:张三 # 年龄:25 # 城市:上海
2.3 原始字符串r—— 一个反斜杠都不用转义!
# 普通字符串:每个 \ 都要转义成 \\ path1 = "c:\\users\\administrator\\desktop\\demo.py" # 原始字符串:加 r,里面所有字符都是原始字符,不用转义 path2 = r"c:\users\administrator\desktop\demo.py" print(path1 == path2) # true
口诀:路径正则加 r,反斜杠全部解脱!
三、字符串操作大全
3.1 索引与切片
msg = "中华人民共和国台湾省" # 索引(正向 0 开始,反向 -1 开始) print(len(msg)) # 10 print(msg[0], msg[9]) # 中 省 print(msg[-1], msg[-10]) # 省 中 # 切片 [start:stop:step] ——含头不含尾 print(msg[7:]) # 台湾省 (从7到最后) print(msg[:7]) # 中华人民共和国 (从0到7) print(msg[2:7]) # 人民共和国 (2到7) print(msg[2:7:2]) # 人共国 (步长2) print(msg[-3:-1]) # 台湾 (倒数第3到倒数第1) print(msg[7:2:-1]) # 省湾台国和 (反向切片) print(msg[::-1]) # 省湾台国和共民人华中 (字符串逆序!)
3.2 index / rindex —— 找不到就报错
s = "hello world hello python"
print(s.index('h')) # 0 (第一个h的位置)
print(s.rindex('h')) # 18 (从右边找,最后一个h的位置)
print(s.index('world')) # 6
# print(s.index('xyz')) # valueerror: substring not found
3.3 find / rfind —— 找不到返回 -1(推荐)
s = "hello world hello python"
print(s.find('h')) # 0
print(s.rfind('h')) # 18
print(s.find('world')) # 6
print(s.find('xyz')) # -1 找不到不报错,返回 -1
# 限定查找区间 [start, end)
print(s.find('o', 5, 15)) # 7 (只在 5~15 范围内找)
3.4 count —— 统计出现次数
s = "hello world hello python"
print(s.count('h')) # 2
print(s.count('hello')) # 2
print(s.count('xyz')) # 0 没出现返回 0
print(s.count('o', 0, 10)) # 2 (限定范围统计)
3.5 大小写魔法
text = "hello world python" print(text.lower()) # hello world python (全小写) print(text.upper()) # hello world python (全大写) print(text.title()) # hello world python (首字母大写) print(text.capitalize()) # hello world python (句首大写) print(text.swapcase()) # hello world python (大小写翻转)
3.6 对齐与填充
title = "python"
# 居中、左对齐、右对齐(参数是总宽度)
print(title.center(20, '-')) # -------python------- (居中,- 填充)
print(title.ljust(20, '=')) # python============== (左对齐)
print(title.rjust(20, '=')) # ==============python (右对齐)
# 零填充(常用于编号)
print("42".zfill(5)) # 00042
print(str(7).zfill(3)) # 007
3.7 开始与结尾判断
filename = "report_2026.pdf"
url = "https://www.baidu.com"
print(filename.startswith("report")) # true
print(filename.endswith(".pdf")) # true
print(url.startswith("https")) # true
print(url.startswith(("http", "https"))) # true (元组多选)
3.8 剔除空白 / 指定字符
# 默认剔除两端空白(空格、\n、\t)
s = " hello world \n"
print(repr(s.strip())) # 'hello world'
print(repr(s.lstrip())) # 'hello world \n' (只去左边)
print(repr(s.rstrip())) # ' hello world' (只去右边)
# 指定要剔除的字符
url = "https://www.example.com/"
print(url.strip('/')) # https://www.example.com (去掉两端 /)
text = "...hello..."
print(text.strip('.')) # hello
3.9 切割与拼接与替换
# split —— 切成列表
csv_line = "张三,25,上海,工程师"
parts = csv_line.split(',')
print(parts) # ['张三', '25', '上海', '工程师']
# join —— 列表拼成字符串
words = ["python", "java", "go"]
result = " | ".join(words)
print(result) # python | java | go
# replace —— 替换
text = "我喜欢苹果,苹果很好吃"
print(text.replace("苹果", "西瓜")) # 我喜欢西瓜,西瓜很好吃
print(text.replace("苹果", "西瓜", 1)) # 我喜欢西瓜,苹果很好吃 (只替换第1个)
3.10 编码与解码
# 编码:字符串 字节流
text = "你好,世界"
encoded = text.encode('utf-8')
print(encoded) # b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
# 解码:字节流 字符串
decoded = encoded.decode('utf-8')
print(decoded) # 你好,世界
print(text == decoded) # true
3.11 is* 系列判断
print("abc123".isalnum()) # true (字母或数字)
print("abc".isalpha()) # true (纯字母)
print("123".isdigit()) # true (纯数字)
print("abc".isupper()) # true (全大写)
print("abc".islower()) # true (全小写)
print("hello world".istitle()) # true (标题格式)
print(" ".isspace()) # true (纯空白)
四、对称字符串判断(实战应用)
综合运用前面讲过的切片和遍历知识:
def is_symmetric(s):
"""判断字符串是否对称(回文)"""
for i in range(len(s) // 2):
if s[i] != s[len(s) - 1 - i]:
return false
return true
# 测试
print(is_symmetric("abcdcba")) # true
print(is_symmetric("abcddcba")) # true
print(is_symmetric("123454321")) # true
print(is_symmetric("12345421")) # false
或者一行搞定:
s = "abcdcba" print(s == s[::-1]) # true 对称!
总结速查表
| 操作类别 | 核心方法 | 一句话 |
|---|---|---|
| 文档注释 | """...""" | 三引号,放在文件/函数/类开头 |
| 原始字符串 | r"..." | 反斜杠不用转义 |
| 查找 | find() / index() | find 找不到返 -1,index 报错 |
| 统计 | count() | 数出现次数 |
| 大小写 | lower() / upper() / title() | 三种变换 |
| 对齐 | center() / ljust() / rjust() / zfill() | 填空凑宽度 |
| 剔除 | strip() / lstrip() / rstrip() | 去空白或指定字符 |
| 切拼换 | split() / join() / replace() | 三件套 |
| 编解码 | encode() / decode() | 字符串 字节流 |
| 判断 | isalpha() / isdigit() / startswith() | 类型和前后缀检测 |
| 逆序 | [::-1] | 反转字符串 |
到此这篇关于python字符串终极指南:三引号与转义字符全解析的文章就介绍到这了,更多相关python字符串操作内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论