字符串操作
主要用于记录学习数据之道出版的python知识手册的相关内容。
字符串的创建
字符串字面值有多种不同的写法:
• 单引号: ‘允许包含有 “双” 引号’
• 双引号: “允许包含有 ‘单’ 引号”
• 三重引号: ‘’‘三重单引号’‘’, “”“三重双引号”“”
使用三重引号的字符串可以跨越多行 —— 其中所有的空白字符都将包含在该字符串字面值中
s1 = 'Tom'
s2 = "字符串创建"
s3 = """
床前明月光
疑似地上霜
"""
print(s1)
print(s2)
print(s3)
访问字符串中的值
字符串(string)支持用切片的方式来访问字符串中的值
s = "life is short"
print(s[1]) #i
print(s[3]) #e
打印的字符串里包括 \ ,因为它是转义字符,所以打印这种字符串,最前面加个 r
print(r".\data")
print(r'D:\no')
print("D:\no")
#结果
.\data
D:\no
D:
o
字符串格式化
Python 支持格式化字符串的输出,一般有 3 种方式可以实现,包括 format ,% ,f-string
# format
name = "Tom"
age = 22
print("my name is {0}, age is {1}".format(name, age))
#结果:
my name is Tom, age is 22
# %
print("my name is %s, age is %s" % (name, age))
#结果:
my name is Tom, age is 22
# f-string
#python 3.6以上支持
print(f"my name is {name}, age is {age}")
#结果:
my name is Tom, age is 22
数字格式化
n1 = 3.1415926
n2 = 31415.926
n3 = 0.31415
n4 = 21
print("保留两位小数:%.2f" %(n1))
print("保留两位小数:{:.2f}".format(n1))
print(f"保留两位小数:{n1:.2f}")
#结果:
保留两位小数:3.14
保留两位小数:3.14
保留两位小数:3.14
#百分比格式
print("百分比格式:{:.2%}".format(n3))
#既有千分位分隔符又有精度设定的数字格式
print("既有千分位分隔符又有小数位数:{:,.2f}".format(n2))
#结果:
百分比格式:31.41%
既有千分位分隔符又有小数位数:31,415.93
#字符串对齐格式,设置默认宽度为8
print('{:>8}'.format(n4)) #右对齐
print('{:<8}'.format(n4)) #左对齐
print('{:^8}'.format(n4)) #居中对齐
#结果:
21
21
21
# 数 字 补 零, 或 者 补 特 定 符 号, 比 如 ‘x’
print("左边补零:{:0>4}".format(n4)) #左边补0, 宽度为4
print("右边补x:{:x<5}".format(n4)) #右边补x,宽度为5
#结果:
左边补零:0021
右边补x:21xxx
字符串基本运算
拼接字符串
s1 = "hello, Tom, "
s2 = "welcome to python"
# 字符串拼接
print(s1+s2)
#结果:
hello, Tom, welcome to python
# 乘法
print(s2 * 2)
#结果:
welcome to pythonwelcome to python
字符串大小写转换
s = "hello, WElcome to PyThon"
#每个单词的首字母大写, title()
print("每个单词的首字母大写:", s.title())
#段落的首字母大写, capitalize()
print("段落的首字母大写:", s.capitalize())
#lower(), 所有字母小写
print("所有字母小写:", s.lower())
#upper(), 所有字母大写
print("所有字母大写:", s.upper())
#大写转小写, 小写转大写
print("大写转小写,小写转大写:",s.swapcase())
#结果:
每个单词的首字母大写: Hello, Welcome To Python
段落的首字母大写: Hello, welcome to python
所有字母小写: hello, welcome to python
所有字母大写: HELLO, WELCOME TO PYTHON
大写转小写,小写转大写: HELLO, weLCOME TO pYtHON
使用换行和制表符
# \n, 表示换行
print("hello,\nwelcome to python")
#结果:
hello,
welcome to python
# \t, 表示制表符,会在字符前保留空白
print("\thello, welcome to python")
#结果:
hello, welcome to python
字符串分割
字符串的分割,通常有 split 和 partition 系列方法
1.split系列
split系列方法包括 split() 、rsplit() 、splitlines()等
split()将一个字符串分隔成多个字符串组成的列表,不含分隔符; rsplit() 的功能与 split() 类似,只不过是从字符串最后面开始分割;splitlines()按照 (\n, \r, \r\n 等)分隔,分割成列表。
s = "hello, welcome to python"
# 按空格分割
s.split()
#结果:
['hello,', 'welcome', 'to', 'python']
# 按某个字符分割
s.split('e')
#结果:
['h', 'llo, w', 'lcom', ' to python']
# 按某个字符分割, 只分割一次
s.rsplit('e', 1)
#结果:
['hello, welcom', ' to python']
#去掉换行符,以换行符分割成列表
print("1+2\n+3+4".splitlines())
#结果:
['1+2', '+3+4']
2.partition系列
partition 系列方法包括 partition() 和 rpartition()
partition() 根据指定的分隔符 (sep) 将字符串进行分割,从字符串左边开始索引分隔符 sep, 索引到则停止索引,返回的是一个包含三个元素的元组 (tuple),即 (head, sep, tail)。
# 遇到一个分割符后就停止索引
print(s.partition('e'))
#结果:
('h', 'e', 'llo, welcome to python')
# 没有遇到分隔符,返回原字符串和两个空字符串
print(s.partition('f'))
#结果:
('hello, welcome to python', '', '')
#rpartition() 的功能与 partition() 类似,只不过是从字符串最后面开始分割
# 遇到第一个分隔符后就停止索引
print(s.rpartition('e'))
# 没 有 遇 到 分 隔 符, 返 回 两 个 空 字 符 串 和 原 字 符 串
print(s.rpartition('f'))
('hello, welcom', 'e', ' to python')
('', '', 'hello, welcome to python')
去掉字符串两边的空白
s = " hello, python "
# 去除字符两端的空白串
s.strip()
'hello, python'
# 去除字符串右侧的空白
s.rstrip()
' hello, python'
# 去除字符串左侧的空白
s.lstrip()
'hello, python '
字符串编码
s1 = "life is 苦短"
#编码encode
s2 = s1.encode(encoding='utf-8')
print(s2)
b'life is \xe8\x8b\xa6\xe7\x9f\xad'
#解码 decode
s2.decode(encoding='utf-8')
'life is 苦短'
is相关方法
• isdigit() 表示字符串内全部为数字
• isalpha() 表示字符串内全部为字符
• isspace() 表示字符串由一个或多个空格组成
• isalnum() 表示字符串内全部为数字和字符
• isinstance(obj,type) 判断一个 object 是什么类型
s4 = 'python'
s5 = '2024'
s6 = 'python2024'
s7 = ' '
s8 = "life is 苦短"
s62 = 'python 2024'
print(s7.isspace())
print(s4.isalpha())
print(s8.isalpha())
print(s6.isalnum())
print(s62.isalnum())
print(isinstance(s4, str))
print(isinstance(s4, (str, int)))
True
True
False
True
False
True
True
其他运算
s = "hello, world"
#统计相同字符的个数
print(s.count('e'))
1
#计算字符串的长度
print(len(s))
12
#字符替换
print(s.replace('l','L'))
heLLo, worLd
# 字 符 替 换 , 只 替 换 指 定 位 置 的 字 符
# replace() 方 法 把 字 符 串 中 的 old ( 旧 字 符 串 ) 替 换 成 new( 新 字 符 串 ) , 如 果 指 定 第 三 个 参 数 max , 则 替 换 不 超 过 max 次 。
print(s.replace('l','L',2))
heLLo, world
# 判断是否以某字符开头,区分大小写
print(s.startswith('h'))
print(s.startswith('%%H'))
True
False
# 判断是否以某字符结尾,区分大小写
s.endswith('a')
False
# join
# string.join(seq) , 以 string 作 为 分 隔 符 , 将 seq 中 所 有 的 元 素 合 并 为 一 个 新 的 字 符 串
'/'.join(s)
'h/e/l/l/o/,/ /w/o/r/l/d'
#返回字符串中最大的字符
max(s)
'w'
#返回字符串中最小的字符
min(s)
' '