Python基础(字符串)
一、字符串的驻留机制
字符串的创建和驻留机制
-
字符串
- 在Python中字符串是基本数据类型,是一个不可变的字符序列(回顾:元祖也是不可变)
-
什么叫字符串的驻留机制呢?
- 仅保存一份相同且不可变字符串的方法,不同的值被存放在字符串的驻留池中,Python的驻留机制对相同的字符串只保留一份拷贝,后续创建相同字符串时,不会开辟新空间,而是把字符串的地址赋给新创建的变量
'''字符串的驻留机制''' print('-----字符串的驻留机制-----') a = 'Python' b = "Python" c = '''Python''' print(a, id(a)) print(b, id(b)) print(c, id(c))
输出:
-----字符串的驻留机制----- Python 1950624969904 Python 1950624969904 Python 1950624969904
同一个id
驻留机制的几种情况(交互模式)
- 字符串的长度为0或1时
- 符合标识符的字符串
- 字符串只在编译时进行驻留,而非运行时
- [-5,256]之间的整数数字
s1 = '' #长度为0
s2 = ''
print(s1 is s2)
输出:
True
s3 = 'a' #长度为1
s4 = 'a'
print(s3 is s4)
输出:
True
- 符合标识符的字符串
s1 ='abcx'
s2 ='abcx'
print(s1 is s2)
print(id(s1))
print(id(s2))
输出:
True
1355948912496
1355948912496
-
什么叫只在编译时驻留?
-
a = 'abc' b = 'ab' + 'c' c = ''.join(['ab','c']) print(a is b) print(a is c) print(type(a)) print(type(c))
输出:
True
False
<class 'str'>
<class 'str'>
-
[-5,256]之间
-
a = -5 b = -5 print(a is b) c = -6 #不在区间内 d = -6 print(c is d)
输出:
True
True
强制驻留
sys中的intern方法强制2个字符串指向同一个对象
import sys
Pycharm对字符串进行了优化处理,不需要import sys
c = 'abc%'
d = 'abc%'
print(c is d)
输出:True
字符串驻留机制的优缺点
- 当需要值相同的字符串时,可以直接从字符串池里面拿来用,避免频繁的创建和销毁,提升效率和节约内存,因此拼接字符串和修改字符串时会比较影响性能的。
- 在需要进行字符串拼接时建议使用str类型的join方法,而非 +,因为join()方法是先计算出所有字符串中的长度,然后再拷贝,只new一次对象,效率要比"+"要高。
二、字符串的常用操作
字符串的查询操作的方法
-
index() 查找子串substr第一次出现的位置,如果查找的字串不存在,则抛出ValueError
-
rindex() 查找字串substr最后一次出现的位置,如果查找的字串不存在,则抛出ValueError
-
find() 查找子串substr第一次出现的位置,如果查找的字串不存在,则返回 -1
-
rfind() 查找子串substr最后一次出现的位置,如果查找的字串不存在,则返回 -1
-
index()
print('-----字符串的查询操作-----')
a = 'hello'
print(a.index('he'))
print(a.index('l'))#第一次出现的位置
输出:
-----字符串的查询操作-----
0
2
如若没有:
print(a.index('x'))
报错:
print(a.index('x'))
ValueError: substring not found
- rindex()
a = 'hello'
print(a.rindex('o'))
输出:4
print(a.rindex('x'))
报错:
print(a.rindex('x'))
ValueError: substring not found
-
find()
a = 'hello' print(a.find('o')) print(a.find('l')) print(a.find('x'))
输出:
4
2
-1
-
rfind()
print('-------') a = 'hello' print(a.rfind('o')) print(a.rfind('l')) print(a.rfind('x'))
输出:
4
3
-1
字符串的大小写转换操作的方法
- upper() 把字符串中所有字符都转成大写字母
- lower() 把字符串中所有字符都转成小写字母
- swapcase() 把字符串中所有字符都转成大写字母,把字符串中所有字符都转成小写字母
- capitalize() 把第一个字符转换为大写,把其余字符转换成小写
- title() 把每个单词的第一个字符转换成大写,把每个单词的剩余字符转换为小写
print('-----字符串大小写转换-----')
s = 'hello,python'
a = s.upper() #转换成大写,会产生一个新的字符串
print(a,id(a)) # HELLO,PYTHON 2330147929072
print(s,id(s)) # hello,python 2330147929136
b = s.lower() #转换之后,会产生一个新的字符串对象
print(b,id(b)) # hello,python 2888227993968
print(s,id(s)) # hello,python 2888227941552
print(b==s) #True
print(b is s) #False
s2 = 'hello,Python'
print(s2.swapcase()) # HELLO,pYTHON
print(s2.capitalize()) # Hello,python
print(s2.title()) # Hello,Python
输出:
-----字符串大小写转换-----
HELLO,PYTHON 2287195192496
hello,python 2287188896944
hello,python 2287195191280
hello,python 2287188896944
True
False
HELLO,pYTHON
Hello,python
Hello,Python
字符串内容对齐操作的方法
- center() 居中对齐,第1个参数指定宽度,第2个参数指定填充符,第2个参数是可选的,默认是空格,如果设置宽度小于实际宽度则返回原字符串
- ljust() 左对齐,第1个参数指定宽度,第2个参数指定填充符,第2个参数是可选的,默认是空格,如果设置宽度小于实际宽度则返回原字符串
- rjust() 右对齐,第1个参数指定宽度,第2个参数指定填充符,第2个参数是可选的,默认是空格,如果设置宽度小于实际宽度则返回原字符串
- zfill() 右对齐,左边用0填充,该方法只接受一个参数,用于指定字符串的宽度,如果指定的宽度小于扥估欧字符串的长度,则返回字符串本身
print('-----字符串对齐操作-----')
s = 'hello,python'
print(s,id(s)) # hello,python 2198579104688
print('-----居中对齐-----')
print(s.center(20,'*')) # ****hello,python****
print(s.center(20)) # hello,python
print(s.center(10)) # hello,python 长度不够,返回原字符串
print(s,id(s)) # hello,python 2198579104688
s1 = s.center(28)
print(s1,id(s1)) # hello,python 2997169685888 这样id就变了
print('-----字符串的左对齐-----')
print(s.ljust(20,'*')) # hello,python********
print(s.ljust(20)) # hello,python
print(s.ljust(10)) # hello,python
print('-----字符串的右对齐-----')
print(s.rjust(20,'*')) # ********hello,python
print(s.rjust(20)) # hello,python
print(s.rjust(10)) # hello,python
print('-----右对齐,使用0进行填充-----')
print(s.zfill(20)) # 00000000hello,python
print(s.zfill(10)) # hello,python
print('-8910'.zfill(8)) # -0008910 在负号的右边,凑八位
字符串的劈分
-
split() 从字符串的左边开始劈分,默认的劈分字符是空格,返回的值都是一个列表
- 以通过参数sep指定劈分字符串是劈分符
- 通过参数maxsplit指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独作为一部分
-
rsplit() 从字符串的右边开始劈分,默认的劈分字符是空格字符串,返回的值都是一个列表
- 以通过参数sep指定劈分字符串是劈分符
- 通过参数maxsplit指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独作为一部分
'''字符串的劈分''' s = 'hello world Python' lst=s.split() print(lst) # ['hello', 'world', 'Python'] 默认以空格劈分 s1 = 'hello|world|Python| 1' print(s1.split(sep='|')) #指定符号劈分 ['hello', 'world', 'Python', ' 1'] print(s1.split(sep='|',maxsplit=2)) #指定劈分两次,剩下的单独做一个字符串元素 ['hello', 'world', 'Python| 1']
输出:
['hello', 'world', 'Python']
['hello', 'world', 'Python', ' 1']
['hello', 'world', 'Python| 1']
rsplit()
rst= s.rsplit()
print(rst) # ['hello', 'world', 'Python']
s1 = 'hello|world|Python| 1'
print(s1.rsplit(sep='|')) # ['hello', 'world', 'Python', ' 1']
print(s1.rsplit(sep='|',maxsplit=2)) # ['hello|world', 'Python', ' 1'] 从右边劈分,但是元素的顺序没变
输出:
['hello', 'world', 'Python']
['hello', 'world', 'Python', ' 1']
['hello|world', 'Python', ' 1']
虽是右劈分,但是元素的排序还是按在原字符串的顺序来
字符串判断
-
判断字符串操作的方法
-
isidentifier() 判断指定的字符串是不是合法的标识符(合法的标识符:字母,数字,下划线)
-
isspace() 判断指定的字符串是否全部由空白字符组成(回车、换行、水平制表符)
-
isalpha() 判断指定的字符串是否全部由字母组成
-
isdecimal() 判断指定字符串是否全部由十进制的数字组成
-
isnumberic() 判断指定的字符串是否全部由数字组成
-
isalnum() 判断指定字符串是否全部由字母和数字组成
print('-----合法标识符------') s='hello,python' print(s.isidentifier()) a='hello_' print(a.isidentifier()) b = '张三_' print(b.isidentifier())
-----合法标识符------
False
True
True
c = ' '
print(c.isspace())
输出:True
print('----isalpha-----')
d='Panda'
print(d.isalpha())
输出:
----isalpha-----
True
print('----isdecimal----')
e = '80'
print(e.isdecimal())
输出:
----isdecimal----
True
print('----isnumberic----')
g='ⅡⅡⅡ'
print(g.isnumeric())
输出:
----isnumberic----
True #罗马数字也是数字
print('-----isalnum-----')
h='asd123'
print(h.isalnum())
i='张三123'
print(i.isalnum())
输出:
-----isalnum-----
True
True
把汉字当字母就完事了
字符串操作的其他方法
-
字符串替换 replace() 第一个参数指定被替换的子串,第二个参数指定替换字串的字符串,该方法返回替换后得到的字符串,替换前的字符串不发生变化,调用该方法时可以通过第个参数指定最大的替换次数
-
字符串的合并 join() 将列表或元祖中的字符串合并成一个字符串
print('----字符串的替换-----')
s='Python,Hello'
print(s.replace('Python','Java')) # Java,Hello
s1='Python,Python,Python'
print(s1.replace('Python','Java',2)) # Java,Java,Python 置换2次
输出:
----字符串的替换-----
Java,Hello
Java,Java,Python
print('-----字符串的合并------')
lst=['hello','Python','world']
print('|'.join(lst)) # hello|Python|world
t = ('hello','Panda','Cat')
print('#'.join(t)) # hello#Panda#Cat
print('*'.join('Python')) # P*y*t*h*o*n
st = {'Ha','La','Ka'}
print('@'.join(st)) # Ha@Ka@La
输出:
-----字符串的合并------
hello|Python|world
hello#Panda#Cat
P*y*t*h*o*n
Ha@Ka@La
三、字符串的比较
- 运算符 : >,>=,<,<=,==,!=
- 比较规则:首先比较两个字符串中的第一个字符,如果相等则继续比较下一个字符,依次比较下去,知道两个字符串中的字符不相等时,其比较结果就是两个字符串的比较结果,两个字串串中的所有后续字符将不再被比较
- 比较原理:两个字符进行比较时,比较的是奇oridinal value(原始值),调用内置函数ord可以得到指定字符的oridinal value. 与内置函数ord对应的是内置函数chr,调用内置函数chr时指定oridinal value可以得到其对应的字符
print('-----字符串的比较-----')
print('apple'>'app') # True
print('apple'>'appLe') # True
print('appLe'>'apple') # False
print('apple'<'pear') # True
print(ord('a')) # 97
print(chr(97)) # a
注意字符串的驻留
四、字符串的切片操作
- 字符串是不可变类型
- 不具备增删改等操作
- 切片操作将产生新的对象
print('-----字符串的切片操作-----')
s = 'hello,Python'
s1 = s[:5]
print(s1) #hello 切到索引5,但是不包括5
s2 = s[6:]
print(s2) #Python 从索引6开始切到末尾
s3 = s[2:6]
print(s3) #llo, 从2到6,不包括6
print(id(s1)) #1749905356464
print(id(s2)) #1749905356400
print(id(s3)) #1749905357040
start,end,step
print('-----切片[start:end:step]----')
s = 'hello,world,python'
print(s[1:5:1]) # ello
print(s[:6:]) # hello,
print(s[6::]) # world,python
print(s[::2]) # hlowrdpto
print(s[6:11:]) # world
print(s[6::2]) # wrdpto
print(s[:10:2]) # hlowr 从索引0开始取,隔一个取一个 10位置上的没取
倒索引的情况
print(s[::-1]) #nohtyp,dlrow,olleh
print(s[-1:-7:-1]) # nohtyp 倒索引,从末尾-1开始
print(s[-1:5:-1]) # nohtyp,dlrow 正负混合索引,负的从末尾-1开始数,正的从头0开始数,任然不包括end位置的
start,end 决定索引头尾的位置,step才决定是正着取还是倒着取
print(s[-6::1]) #python 从-6位置一直取到最后,并没有因为开头索引是负数就倒着取
五、格式化字符串
- 为什么需要格式化字符串
- 有些字符串是模板,但是内容待填
%作占位符
'''格式化字符串'''
'''%作占位符
%s 字符串
%i或者%d 整数
%f 浮点数
'''
name='张三'
age=20
print('我叫%s,今年%d岁' %(name,age))
输出:我叫张三,今年20岁
{}作占位符
'''
{}作占位符
'''
name='张三'
age=20
print('我叫{},今年{}岁'.format(name,age))
输出:我叫张三,今年20岁
#f-string
print(f'我叫{name},今年{age}岁')
输出:我叫张三,今年20岁
宽度和精度
-
特殊:宽度限制
print('%10d' % 99) # 99 表明确实限制为10个字符宽度 print('hellohello') #hellohello print('%10d' % 789) # 789
-
小数情况
print('%.3f' % 3.14159) #3.142 表明保留三位小数,并且末尾四舍五入
-
同时表示宽度和精度
print('%10.3f' % 3.1415926) # 3.142 加上小数共计10个字符宽度,小数四舍五入,保留3位 print('%10.3f' % 12345678910.14159) #12345678910.142整数位数超过宽度的情况
-
{}表示宽度和精度
print('{0:.3}'.format(3.14159)) #3.14 这里的参数.3表示一共三位数 print('{0:.3f}'.format(3.14159)) #3.142 这才是表示3位小数 print('{:.3f}'.format(3.14159)) #3.142 第一个参数0可以省略不写 print('{:10.3f}'.format(3.14159)) # 3.142 与下面对比证明是带小数点和小数一共10位 print('hellohello') #hellohello
输出:
3.14
3.142
3.142
3.142
hellohello
六、字符串的编码转换
-
为什么需要字符串的编码转换
不同计算机之间以byte字节传输 不同计算机内使用的字符集不一样
-
编码与解码的方式
- 编码:将字符串转换为二进制数据(bytes)
- 解码:将bytes类型的数据转换成字符串类型
s='天涯共此时' #编码 print(s.encode(encoding='GBK')) #在GBK中一个中文占两个字节 print(s.encode(encoding='UTF-8')) #在UTF-8中一个中文占三个字节 #解码 #byte就代表是一个二进制数据(字节类型数据) byte=s.encode(encoding='UTF-8') #编码 print(byte) print(byte.decode(encoding='UTF-8')) #解码
用什么编码就用什么解码