侧边栏壁纸
博主头像
phphi

phphi's blog

  • 累计撰写 51 篇文章
  • 累计收到 0 条评论

Day11 - 常用数据结构之字符串

2026-4-24 / 0 评论 / 1 阅读

常用数据结构之字符串

字符串基础

字符串是由零个或多个字符组成的有序序列,用单引号或双引号创建:

s1 = 'hello, world!'
s2 = "你好,世界!"
s3 = '''hello,
wonderful
world!'''           # 三引号,支持多行

注意:字符串是不可变类型,不能通过索引修改字符。

转义字符

转义符 含义
\\ 反斜杠
\' 单引号
\" 双引号
\n 换行
\t 制表符
\r 回车
\x61 十六进制表示字符
\u9a86 Unicode字符

原始字符串(不转义):

s = r'hello\nworld'   # \n 不是换行,就是字符\和n

字符串运算

# 拼接和重复
print('a' + 'b')      # ab
print('-' * 10)       # ----------

# 比较(按Unicode编码比较)
print('A' < 'a')      # True(65 < 97)

# 成员运算
print('wo' in 'hello world')  # True

# 索引和切片
s = 'abc123456'
print(s[0])           # a
print(s[-1])          # 6
print(s[2:5])         # c12
print(s[::-1])        # 654321cba(反转)

字符串方法

大小写转换

s = 'hello, world!'
print(s.capitalize())  # Hello, world!(首字母大写)
print(s.title())        # Hello, World!(每个单词首字母大写)
print(s.upper())        # HELLO, WORLD!
print('GOOD'.lower())   # good

查找

s = 'hello, world!'
print(s.find('or'))      # 8(找不到返回-1)
print(s.rfind('o'))      # 8(从右向左找)
print(s.index('or'))     # 8(找不到抛异常)

性质判断

s = 'abc123'
print(s.isdigit())   # False(是否全为数字)
print(s.isalpha())   # False(是否全为字母)
print(s.isalnum())   # True(是否由字母或数字组成)
print('hello'.startswith('he'))  # True
print('hello.py'.endswith('.py'))  # True

格式化

f-string(推荐,Python 3.6+):

name = 'Alice'
age = 30
print(f'{name} is {age} years old')
print(f'{3.14159:.2f}')      # 3.14(保留两位小数)
print(f'{100:0>5d}')          # 00100(补零)
print(f'{0.75:.1%}')           # 75.0%(百分比)
print(f'{123456:,}')          # 123,456(千分位)

修剪

s = '   hello   '
print(s.strip())     # hello(去除两端空格)
print(s.lstrip())    # 'hello   '
print(s.rstrip())    # '   hello'

替换和拆分

s = 'hello, good world'
print(s.replace('o', '@'))         # hell@, g@@d w@rld
print(s.replace('o', '@', 1))      # hell@, good world(替换1次)

s2 = 'I love you'
print(s2.split())                  # ['I', 'love', 'you']
print('-'.join(['I', 'love', 'you']))  # I-love-you

编码和解码

s = '骆昊'
b = s.encode('utf-8')   # b'\xe9\xaa\x86\xe6\x98\x8a'
print(b.decode('utf-8'))  # 骆昊

注意:编码和解码方式必须一致,否则会乱码或报错。

总结

  • 字符串是不可变的有序序列,支持索引、切片、拼接操作
  • 常用方法:大小写、查找、判断、格式化、修剪、替换、拆分
  • 格式化推荐用 f-string:f'{变量:.2f}'
  • 字符串与字节串可通过 encode()/decode() 相互转换