Python字符串完全指南:从基础到进阶
📝 一文搞懂Python字符串的声明、索引切片、常用操作,附赠实战案例!
📌 目录
-
一、字符串基础
-
二、索引与切片
-
三、字符串常用操作
-
四、实战案例
一、字符串基础
1. 字符串的声明方式
Python支持四种字符串声明方式:
python
# 单引号
s1 = 'hello world'
# 双引号
s2 = "hello world"
# 三引号(可换行)
s3 = """hello world"""
s4 = '''
hello
world
'''
print(s4) # 保留换行和缩进
2. 转义字符
| 转义字符 | 说明 | 示例 |
|---|---|---|
\' | 单引号 | 'it\'s' |
\" | 双引号 | "say \"hi\"" |
\n | 换行 | "a\nb" |
\t | 制表符 | "a\tb" |
\\ | 反斜杠 | "C:\\Users" |
r"" | 原始字符串 | r"C:\Users" |
python
# 转义示例
print("hello\nworld") # 换行
print("C:\\Program Files") # 反斜杠
print(r"C:\Users\Admin") # 原始字符串,\不转义
3. 字符串格式化
三种常用格式化方式:
python
name = "qiku"
age = 1
addr = "东三街"
# 方式1:f-string(推荐)
print(f"名字叫{name},年纪是{age},地址是{addr}")
# 方式2:%格式化
print("名字叫%s,年纪是%s,地址是%s" % (name, age, addr))
# 方式3:format方法
print("名字叫{},年纪是{},地址是{}".format(name, age, addr))
二、索引与切片
1. 索引(正索引和负索引)
python
msg = "中华人民共和国河南省" print(len(msg)) # 10 # 正索引:从0开始 print(msg[0]) # 中 print(msg[9]) # 省 # 负索引:从-1开始 print(msg[-1]) # 省 print(msg[-10]) # 中
2. 遍历字符串
python
msg = "中华人民共和国河南省"
# 方式1:直接遍历字符
for e in msg:
print(e)
# 方式2:通过索引遍历
for i in range(len(msg)):
print(i, msg[i])
3. 切片操作
切片语法:[start:stop:step]
-
start:开始索引(包含) -
stop:结束索引(不包含) -
step:步长(默认为1)
python
msg = "中华人民共和国河南省" print(msg[7:]) # 河南省(从索引7到末尾) print(msg[:7]) # 中华人民共(从开头到索引6) print(msg[2:7]) # 人民共和国(索引2到6) print(msg[2:7:2]) # 人共国(步长为2) print(msg[::-1]) # 省南河国共和人华中(反转) print(msg[-3:-1]) # 河南(负索引切片)
4. 实战:判断对称字符串
python
s = "12345421"
for i in range(len(s) // 2):
if s[i] != s[len(s) - 1 - i]:
print(f"字符{s[i]}与字符{s[len(s) - 1 - i]}不一致")
break
else:
print("是对称字符串")
三、字符串常用操作
1. 查找类方法
| 方法 | 说明 | 示例 |
|---|---|---|
index(sub) | 返回索引,找不到报错 | "hello".index("l") → 2 |
rindex(sub) | 从右侧查找索引 | "hello".rindex("l") → 3 |
find(sub) | 返回索引,找不到返回-1 | "hello".find("x") → -1 |
rfind(sub) | 从右侧查找,找不到返回-1 | "hello".rfind("l") → 3 |
count(sub) | 统计子串出现次数 | "hello".count("l") → 2 |
python
s = "hello world"
print(s.index("llo")) # 2
print(s.rindex("l")) # 9(从右数第一个l的位置)
print(s.find("llo")) # 2
print(s.find("xxx")) # -1
print(s.count("l")) # 3
2. 大小写转换
python
s = "heLlo WorlD" print(s.lower()) # hello world(全部小写) print(s.upper()) # HELLO WORLD(全部大写) print(s.title()) # Hello World(单词首字母大写) print(s.capitalize()) # Hello world(首字母大写) print(s.swapcase()) # HElLO wORLd(大小写互换)
3. 对齐方法
python
s = "hello" print(s.center(20, "*")) # *******hello********(居中) print(s.ljust(20, "*")) # hello***************(左对齐) print(s.rjust(20, "*")) # ***************hello(右对齐) print(s.zfill(20)) # 000000000000000hello(右侧填0)
4. 判断开头/结尾
python
s = " hello world "
print(s.startswith(" ")) # True
print(s.endswith(" ")) # True
5. 剔除指定字符
python
s = "+++hello world+++"
print(s.strip("+")) # hello world(去除两端+)
print(s.lstrip("+")) # hello world+++(去除左侧+)
print(s.rstrip("+")) # +++hello world(去除右侧+)
print(" hello ".strip()) # hello(默认去除空格)
6. 切割与拼接
python
# 拼接
print("++".join("hello")) # h++e++l++l++o
print(" ".join(["hello","world"])) # hello world
# 切割
print("hello world".split()) # ['hello', 'world'](默认空格)
print("hello world".split('l')) # ['he', '', 'o wor', 'd']
# 替换
print("hello hello".replace("hello", "hi")) # hi hi
print("hello hello".replace("hello", "hi", 1)) # hi hello(只替换1次)
7. 编码与解码
python
# 编码:字符串 → 字节
text = "hello 中国"
print(text.encode("utf-8")) # b'hello \xe4\xb8\xad\xe5\x9b\xbd'
print(text.encode("gbk")) # b'hello \xd6\xd0\xb9\xfa'
# 解码:字节 → 字符串
byte_data = b'hello \xe4\xb8\xad\xe5\x9b\xbd'
print(byte_data.decode("utf-8")) # hello 中国
8. 类型判断
python
print("abc".isalpha()) # True(全是字母)
print("123".isdigit()) # True(全是数字)
print("abc123".isalnum()) # True(字母或数字)
print("Abc".islower()) # False(是否全小写)
print("ABC".isupper()) # True(是否全大写)
print("Hello World".istitle()) # True(是否每个单词首字母大写)
四、实战案例
案例1:清理用户输入
python
# 去除首尾空格、统一大小写 user_input = " HeLLo WorlD " clean = user_input.strip().lower() print(clean) # hello world
案例2:敏感词过滤
python
text = "你是个笨蛋,真是个傻瓜"
bad_words = ["笨蛋", "傻瓜"]
for word in bad_words:
text = text.replace(word, "***")
print(text) # 你是个***,真是个***
案例3:提取文件信息
python
filename = "2026-07-15_报告.pdf"
# 提取文件名和扩展名
name = filename.split(".")[0] # 2026-07-15_报告
ext = filename.split(".")[1] # pdf
# 提取日期
date = name.split("_")[0] # 2026-07-15
print(f"日期:{date},文件类型:{ext}")
📊 快速速查表
字符串常用方法分类
| 分类 | 方法 |
|---|---|
| 查找 | index(), rindex(), find(), rfind(), count() |
| 大小写 | lower(), upper(), title(), capitalize(), swapcase() |
| 对齐 | center(), ljust(), rjust(), zfill() |
| 判断 | startswith(), endswith(), isalpha(), isdigit(), isalnum() |
| 清理 | strip(), lstrip(), rstrip() |
| 切割/拼接/替换 | split(), join(), replace() |
| 编码/解码 | encode(), decode() |
💡 小贴士:字符串是不可变类型,所有方法都返回新字符串,不会修改原字符串!
如果觉得有用,欢迎点赞收藏! ⭐ 更多Python干货持续更新中~ 🚀
809



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



