05_字符串
字符串
基本操作
s = "hello"
lst = list(s) # 字符串转列表
# 大小写转换
s.upper() # 转大写
s.lower() # 转小写
s.capitalize() # 首字母大写
s.swapcase() # 大小写互换
# 去除空白
s.strip() # 去除首尾空白
s.lstrip() # 去除左边空白
s.rstrip() # 去除右边空白查找与替换
# 查找
s.find('a') # 返回第一个 'a' 的索引,不存在返回 -1
s.rfind('a') # 从右边找
s.index('a') # 同 find,但不存在会报错
s.count('a') # 统计字符出现次数
s.count('abc') # 统计子串出现次数
# 替换
s.replace('old', 'new') # 替换所有
s.replace('old', 'new', 1) # 只替换第一个
s.replace(c, ' ') # 字符替换为空格判断方法
# 字符/字符串判断
'a'.isdigit() # 单字符判断:False
'5'.isdigit() # 数字字符:True
s.isdigit() # 全是数字
s.isalpha() # 全是字母
s.islower() # 全是小写
s.isupper() # 全是大写
# 回文判断
s == s[::-1] # 字符串是否回文格式化与对齐
# 填充对齐
s = s.ljust(width, '0') # 左边补 '0' 到指定长度
s = s.rjust(width, '0') # 右边补 '0'
s = s.center(width, '0') # 居中补 '0'
# 补零
s = s.zfill(5) # 左边补 '0' 到宽度 5
# 分割与连接
s.split() # 按空白分割(默认)
s = ' '.join(lst) # 用空格连接(⚠️ lst 必须是字符串列表!)
s = ''.join(lst) # 直接连接
# ⚠️ join() 要求所有元素都是字符串
nums = [1, 2, 3]
# ' '.join(nums) # ❌ TypeError: sequence item 0: expected str instance, int found
' '.join(map(str, nums)) # ✅ '1 2 3'去重与排序
# 字符串去重(保持顺序)
s = ''.join(dict.fromkeys(s))
# 字符串排序
sorted_s = ''.join(sorted(s)) # 按字符排序
words.sort() # 列表按字典序排序
# Python 字符串默认按字典序比较:'A' < 'Z' < 'a' < 'z'sorted(st)把字符串st的字符按字母顺序排序,返回一个字符列表。- 例如
st = "eat",sorted("eat")得到['a', 'e', 't']。
- 例如
"".join(...)把字符列表拼接成一个字符串。- 得到
"aet"。
- 得到
ASCII 码与进制转换
# ord() 和 chr()
ord('A') # 字符转 ASCII 码: 65
chr(97) # ASCII 码转字符: 'a'
# 字母序号转换(A-Z → 0-25)
ord('A') - ord('A') # 0
# 数字字符转数字
int('5') # 5
ord('5') - ord('0') # 5
# 进制转换
int("FF", 16) # 十六进制转十进制: 255
int("101", 2) # 二进制转十进制: 5
int("77", 8) # 八进制转十进制: 63
# 十进制转其他进制
bin(255) # '0b11111111'
oct(255) # '0o377'
hex(255) # '0xff'最长数字子串
import re
# 提取连续数字串
s = "abc123xyz456"
arr = re.findall(r'\d+', s) # ['123', '456']
# 找最长数字子串
max_len = max(len(x) for x in arr)
res = ''.join(x for x in arr if len(x) == max_len)05_字符串
https://mingsm17518.github.io/2026/11/03/算法学习/01_数据结构/05_字符串/