Python字符串
字符串
- 索引
- 正索引:第一位索引为0,最后一位索引为n-1
- 负索引:第一位索引为-n,最后一位索引为-1
- 循环字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14# 第一种
def codesum(s):
total = 0
for c in s:
total = total + ord(c)
return total
codesum('Hello')
# 第二种
def codesum(s):
total = 0
for i in range(len(s)):
total = total + ord(s[i])
return total
codesum('Hello') - 常用的转义字符:每个转义字符长度为1
1
2
3
4
5
6
7\\ 反斜杠
\' 单引号
\" 双引号
\n 换行符
\r 回车
\t 水平制表符
print('\\我是\"Henry\"') - 字符串切片
- 格式:s[begin:end]返回begin到end-1的字符串
- 获取索引i对应的字符可以使用s[i]或s[i:i+1]
- 如果是s[i:i+1]形式,则i可以为任意整数不会报错,但s[i]形式,则i必须符合字符数量要求,否则报错
- 如果是s[i:i+1]形式,若省略起始索引,则默认起始索引为0;若省略终止索引,则默认提取到字符串末尾;如果起始和结束都省略,则获取全部字符串
1
2
3
4
5
6
7
8
9
10
11
12
13food = 'apple pie'
food[6:19]
# 'pie'
food[-3:7] # 取[-3:-1]和[0:7]的交集
# 'p'
def get_ext(fname):
dot = fname.rfind('.')
if dot == -1:
return ''
else:
return fname[dot+1:]
get_ext('helo.text')
# 'text'
- 常用测试函数
1
2
3
4
5
6
7s.endwith(t) # s以字符串t结尾
s.startswith(t) # s以字符串t大头
s.isalnum() # s只包含字母或数字
s.isalpha() # s只包含字母
s.isdecimal() # s只包含表示十进制数字的字符
s.issupper() # s只包含大写字母
t in s # s包含字符串t - 常用搜索函数
1
2
3
4s.find(t) # 如果没有找到字符串t,则返回-1;否则返回t在s中的起始位置
s.rfind(t) # 与find相同,但从右往左搜索
s.index(t) # 与find相同,但如果s中找不到t,则会引发ValueError异常
s.rindex(t) # 与index相同,但从右往左 - 改变大小写函数
1
2
3
4
5s.capitalize() # 将s[0]改为大写
s.lower() # 将s所有字母改小写
s.upper() # 将s所有字母改大写
s.swapcase() # 将s中字母小写改大写,大写改小写
s.title() # 让s的到小写符合头衔的要求 - 设置格式函数
1
2
3
4
5
6
7
8s.center(n, ch) # 包含n个字符的字符串,其中s位于中央,两边字符ch填充
s.ljust(n, ch) # 包含n个字符的字符串,其中s位于左边,右边用字符ch填充
s.rjust(n, ch) # 包含n个字符的字符串,其中s位于右边,左边用字符ch填充
s.format(vars) # 多种用法
print('{0} likes {1}'.format('Jack', 'ice cream'))
# 'Jack likes ice cream'
print('{who} likes {eat}'.format(who = 'Jack', eat = 'ice cream'))
# 'Jack likes ice cream' - 剥除函数
1
2
3
4
5
6s.strip(ch) # 从s开头和末尾删除所有连续包含在字符串ch中的字符
s.lstrip(ch) # 从s开头(左端)删除所有连续包含在字符串ch中的字符
s.rstrip(ch) # 从s结尾(右端)删除所有连续包含在字符串ch中的字符
s = 'abcde
s.strip('acdfg')
# 'bcde' - 拆分函数
1
2
3
4
5s.partition(t) # 从默认左侧开始搜索第一个t,将s拆分为三个字符串(head、t、tail),head为t前面的字符串,tail为t后面的字符串
s.rpartition(t) # 与partition相同,但从s右端开始搜索
s.split(ch) # 以t为分隔符,将s划分为一系列字符串,并返回这些字符串的列表。若ch为空,则默认以空格分割
s.rsplit(ch) # 与split相同,但从右端开始搜索t
s.splitlines()# 返回一个由s中各行组成的列表 - 替换函数
1
2s.replace(old,new) # 将s中的每个old替换为new
s.expendtabs(n) # 将s中的每个制表符替换为n个空格 - 其他函数
1
2
3
4
5
6
7
8
9
10s.count(t) # t在s中出现的次数
s.encode() # 设置s的编码
s.join(seq) # 使用s将seq中的字符串连接成一个字符串
s.maketrans(old,new)# 创建一个转换表,用于将old中的字符串改为new中相应的字符:注意,s可以是任何字符串,不影响返回的转换表
s.translate(table) # 使用指定转换表对应s中的字符进行替换
sl.zfill(width) # 在s左边添加足够多的0,让字符串的长度为width
'-'.join(['one', 'again'])
# one-again
'23'.zfill(4)
# '0023' - 常用正则表达式
1
2
3
4xy? # x、xy
x|y # x、y
x* # ''、x、xx...
x+ # x、xx... - 正则表达式匹配字符串
1
2
3
4
5
6
7
8import re
def ff(s):
return re.match('(ha)+!+', s) != None
print(ff('hahaha!!!'))
# True
print(ff('haaaaa!!!'))
# False
- 标题: Python字符串
- 作者: Henry
- 创建于 : 2026-01-03 20:39:58
- 更新于 : 2026-01-11 07:57:52
- 链接: https://mybetterworks.github.io/2026/01/03/Python字符串/
- 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论