📚 Python 字符串(String)完整笔记

字符串(str)是 Python 中用于表示文本的 不可变有序序列,支持索引、切片、遍历和丰富的方法操作。


一、字符串的基本特性

✅ 不可变性(Immutable)

  • 一旦创建,不能修改原字符串内容
  • 所有“修改”操作(如 replace)都返回新字符串
s = "hello"
s[0] = "H"  # ❌ 报错!TypeError: 'str' object does not support item assignment

✅ 有序 & 支持索引

  • 可通过正向索引0, 1, 2...)或负向索引-1, -2...)访问字符
my_str = "hang123asd"
print(my_str[0])   # 'h'
print(my_str[-1])  # 'd'

二、常用字符串方法

1. 查找:index(sub) / find(sub)

  • index(sub):返回子串首次出现的索引不存在则报错
  • find(sub):不存在返回 -1(更安全)
s = "hang123asd"
print(s.index("h"))  # 0
print(s.find("x"))   # -1(不报错)

💡 建议:不确定是否存在时,用 find() 避免异常。


2. 替换:replace(old, new[, count])

  • 返回新字符串,原字符串不变
  • 可选参数 count:最多替换次数
s = "hang123asd"
new_s = s.replace("h", "l")
print(new_s)  # "lang123asd"

# 只替换第一个 "it"
text = "it it it"
print(text.replace("it", "IT", 1))  # "IT it it"

3. 分割:split(sep)

  • 按分隔符 sep 将字符串拆分为列表
  • 默认按任意空白字符(空格、换行、制表符)分割
s = "hang 123 asd"
lst = s.split(" ")
print(lst)        # ['hang', '123', 'asd']
print(type(lst))  # <class 'list'>

# 默认分割(处理多个空格)
s2 = "a   b\tc\n d"
print(s2.split())  # ['a', 'b', 'c', 'd']

🔁 逆操作"分隔符".join(列表) → 拼接字符串

words = ['a', 'b', 'c']
print("-".join(words))  # "a-b-c"

4. 去除两端字符:strip([chars])

  • 默认:去除两端空白字符(空格、换行等)
  • 指定 chars:去除两端属于 chars 集合的字符(不是子串!)
# 去空格
s = "   hello   "
print(s.strip())  # "hello"

# 去指定字符(注意:是字符集合!)
s = "hang 123 gnah"
print(s.strip("hang"))  # " 123 " 
# 解释:从两端删除 'h','a','n','g',直到遇到空格(不在集合中)
⚠️ 常见误区
"www.example.com".strip("w.com")  # 结果是 "example"(不是 "example"!)
# 实际删除了两端所有 w, ., c, o, m 字符

只去空格? → 用 strip() 无参数
去特定子串? → 用 removeprefix() / removesuffix()(Python 3.9+)


5. 统计:count(sub)

  • 统计子串 sub 在字符串中出现的次数
s = "hang 123 h"
print(s.count("h"))  # 2(区分大小写)

6. 长度:len(str)

  • 返回字符串总字符数(包括空格、标点)
s = "hang 123 h"
print(len(s))  # 10

三、字符串遍历

while 循环(通过索引)

my_str = "hang 123"
index = 0
while index < len(my_str):
    print(my_str[index])
    index += 1

for 循环(推荐)

for char in my_str:
    print(char)

📌 建议:优先使用 for 循环,代码更简洁安全。


四、综合练习解析

str1 = "itheima itcast boxuegu"

# 1. 统计 "it" 出现次数
count_str = str1.count("it")  # 2("itheima" 和 "itcast" 各一个)

# 2. 替换空格为 "|"
replace_str = str1.replace(" ", "|")  # "itheima|itcast|boxuegu"

# 3. 按 "|" 分割
split_str = replace_str.split("|")    # ['itheima', 'itcast', 'boxuegu']

💡 更简洁写法

str1.split()  # 直接按空格分割,无需 replace

五、拓展知识点

1. 字符串格式化

  • f-string(推荐)
    name = "Alice"
    age = 25
    print(f"Hello, {name}! You are {age} years old.")
    
  • .format()
    print("Hello, {}!".format(name))
    

2. 大小写转换

s = "Hello World"
print(s.upper())    # "HELLO WORLD"
print(s.lower())    # "hello world"
print(s.capitalize())  # "Hello world"

3. 判断方法

"123".isdigit()     # True
"abc".isalpha()     # True
"abc123".isalnum()  # True
"   ".isspace()     # True

4. 前缀/后缀检查

url = "https://example.com"
print(url.startswith("https"))  # True
print(url.endswith(".com"))     # True

5. 原始字符串(Raw String)

  • r"" 避免转义(常用于正则、路径)
path = r"C:\new_folder\test"  # 不会将 \n 视为换行

六、字符串 vs 其他序列

特性字符串(str)列表(list)元组(tuple)
可变性❌ 不可变✅ 可变❌ 不可变
元素类型必须是字符任意类型任意类型
常用方法replace, split, stripappend, removeindex, count
性能高(不可变)高(不可变)

✅ 总结口诀

“字符串不可变,索引负向也行;
查找用 index,替换得新串;
分割成列表,strip 去两端;
遍历 for 最好,综合练熟练!”

掌握这些,你就能高效处理 Python 中的文本数据了!

更多推荐