字符串(str)作为不可变序列,支持索引、切片、拼接、比较、成员运算等多种操作。这些基础操作是文本处理的核心。
一、索引与切片
通过下标 [] 和切片 [:] 访问子串,支持正向、反向索引和步长。
s = "python"
print(s[0]) # p,第一个字符
print(s[-1]) # n,最后一个字符
print(s[1:4]) # yth,切片(左闭右开)
print(s[::-1]) # nohtyp,反转二、拼接与重复
使用 + 拼接字符串,使用 * 重复字符串。
a, b = "Hello", "World"
print(a + " " + b) # Hello World
print("Hi! " * 3) # Hi! Hi! Hi!三、比较运算
字符串比较基于 Unicode 编码顺序,可使用 ==、!=、<、> 等关系运算符进行比较。
print("apple" == "apple") # True
print("apple" < "banana") # True
print("Zoo" > "apple") # False(因为 'Z' < 'a' 的编码值)四、成员运算
使用 in、not in 判断子串是否存在。
s = "banana"
print("na" in s) # True
print("xy" not in s) # True五、遍历字符串
字符串是可迭代对象,可用 for 循环逐字符访问。
for ch in "hi":
print(ch)
# h
# i六 、查找与统计
使用字符串方法 find() 定位子串,count() 统计出现次数。
s = "banana"
print(s.find("na")) # 2
print(s.count("na")) # 2七、使用内置函数和方法
1、内置函数
许多内置函数可直接用于字符串:
s = "banana"
print(len(s)) # 6
print(max(s)) # n
print(min(s)) # a
print(sorted(s)) # ['a', 'a', 'a', 'b', 'n', 'n']2、str 类的方法
str 类提供了大量的方法来处理字符串,比如大小写转换、去除空白或指定字符以及拆分与拼接等。
# 大小写转换
print("Hello".lower()) # hello
print("Hello".upper()) # HELLO
# 去除空白或指定字符
print(" hello ".strip()) # "hello"
print("xxhelloxx".strip("x")) # "hello"
# 拆分与拼接
s = "a b c"
print(s.split()) # ['a', 'b', 'c']
print("-".join(["a", "b", "c"])) # a-b-c详情请参阅:
⚠️常见操作误区
1、索引越界
s = "abc"
# print(s[5]) # ❌ IndexError: string index out of range2、不可变性误解
很多初学者尝试直接修改字符,其实字符串不可变,只能通过拼接、切片等生成新对象。
s = "python"
# s[0] = "P" ❌ TypeError: 'str' object does not support item assignment
s = "P" + s[1:] # ✅ 生成新字符串
print(s) # Python3、数字拼接错误
s = "age: " + 18 # ❌ TypeError: can only concatenate str (not "int") to str正确写法:
s = "age: " + str(18) # age: 184、大小写比较陷阱
"Zoo" < "apple" 的结果是 True,因为比较基于 Unicode 编码,不是自然语言规则。
需要无视大小写时,应该先统一 lower() 或 casefold()。
小结
字符串是不可变的有序序列。
索引与切片:通过 [] 和 [:] 访问子串,支持正向、反向和步长
拼接与重复:用 + 拼接,用 * 重复生成
比较与成员运算:比较基于 Unicode 编码,in / not in 判断子串是否存在
遍历与统计:字符串可迭代,可结合 find()、count() 等方法快速检索
内置函数与方法:常用 len()、sorted() 以及 strip()、split()、join() 等方法
“点赞有美意,赞赏是鼓励”
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.