图片说明

字符串的驻留机制

仅保存一份相同且不可变字符串的方法,不同的值被存放在字符串的驻留池中,Python的驻留机制对相同的字符串只保留一份拷贝,后续的创建不会开辟新的空间。例如:

a='Python'
b="Python"
c='''Python'''
print(a,id(a))
print(b,id(b))
print(c,id(c))        #地址id都是相同的

驻留机制的几种情况(交互模式)
1 字符串的长度为0或者1 时
2 符合标识符的字符串
3 字符串只在编译时进行驻留,而非运行时
4 [-5,256]之间的整数数字

当需要值相同的字符串时,可以直接从字符串池里拿来使用,避免频繁的创建和销毁,提升效率和节约内存,因此拼接字符串和修改字符串时比较影响性能的。
在需要进行字符串拼接操作时建议使用str类型的join方法,而非+,因为join()方法是先计算出所有字符中的长度,然后再拷贝,只new一次对象,效率比“+”高。

字符串的查询操作的方法

1.index()查找子串substr第一次出现的位置,如果查找的子串不存在时,则抛出valueerror
2.rindex()查找子串substr最后一次出现的位置,如果查找的子串不存在时,则抛出valueerror
3.find()查找子串substr第一次出现的位置,如果查找的子串不存在时,则抛出-1
4.rfind()查找子串substr最后一次出现的位置,如果查找的子串不存在时,则抛出-1

s='hello,hello'
print(s.index('lo'))       #3
print(s.find('lo'))       #3
print(s.rindex('lo'))       #9
print(s.rfind('lo'))       #9    相当于给出的是索引的位置 0 1 2

print(s.find('k'))     #-1,不会报错
#print(s.index('k'))     报错 ValueError: substring not found

字符串中大小写转换的操作方式

1 upper(),转换成大写,产生一个新的字符串

s='hello,python'
a=s.upper()               
print(a,id(a))       #HELLO,PYTHON 2418367708400
print(s,id(s))       #hello,python 2418367708272

2 lower(),转化成小写,#产生一个新的字符串

s='Hello,python'
a=a.lower()            
print(a,id(a))
print(s,id(s))

3 swapcase() 所有大写改成小写,小写改成大写

s='Hello,python'
a=s.swapcase()
print(a,id(a))

4 capitalize() 把第一个字符换成大写,其他的换成小写

s='Hello,python'
a=s.capitalize()
print(a,id(a))

5 title()把每一个单词的第一个字符换成大写,每个单词的剩余字符转换为小写

a=s.title()
print(a,id(a))

字符串内容对齐操作

1.center()
居中对齐,第一个参数指定宽度,第二个参数指定填充符,如果设计宽度小于实际宽度,则返回原来的字符串

s='Hello,python。'
print(s.center(20,'*')) #***Hello,python。****

print(s.center(10,'*'))            #如果设计宽度小于实际宽度,则返回原来的字符串

2.ljust()左对齐

s='Hello,python。'
print(s.ljust(100,'*'))

3.rjust()右对齐

s='Hello,python。'
print(s.rjust(100,'*'))

4zfill() 右对齐,用0 填充

s='Hello,python。'
print(s.zfill(100))

字符串劈分操作

1.split() 从字符串的左边开始劈分,默认的劈分字符是空格,返回的值是列表。
通过参数sep指定劈分的字符串是劈分符
通过参数maxsplit指定劈分字符串时最大劈分次数,经过最大劈分次数后,剩余的子串会单独作为一部分

s='hello world Python'

lst=s.split()
print(lst) #['hello', 'world', 'Python']

s1='hello|world|Python'
print(s1.split(sep='|'))   #['hello', 'world', 'Python']
print(s1.split(sep='|',maxsplit=1))   #['hello', 'world|Python']

rsplit() 从字符串的右边开始劈分,默认的劈分字符是空格,返回的值是列表
通过参数sep指定劈分的字符串是劈分符
通过参数maxsplit指定劈分字符串时最大劈分次数,经过最大劈分次数后,剩余的子串会单独作为一部分

s='hello world Python'
print(s1.rsplit(sep='|',maxsplit=1))

判断字符串的相关方法

1.isidentifier() 判断指定的字符是不是合法的标识符

s='hello world Python'
print('1.',s.isidentifier())      #False
print('2.','hello'.isidentifier())  #True
print('3.','张三_'.isidentifier())  #True
print('4.','张三_123'.isidentifier())           #True

2.isspace() 判断指定的字符是否由空白字符(回车,换行,水平制表符)组成

print('5.','\t'.isspace())      #False

3.isalpha() 判断指定的字符串是否全部由字母组成

print('6.','abc'.isalpha())          #True
print('7.','张三'.isalpha())          #True
print('8.','张三1'.isalpha())      #False

4.isdecimal() 判断指定的字符串是否全部由十进制数组成

print('9.','123'.isdecimal())          #True
print('10.','123四'.isdecimal())      #False
print('11.','ⅠⅡⅢ'.isdecimal())      #False
  1. isnumeric() 判断指定的字符串是否全部由数字组成
print('12.','123'.isnumeric())          #True
print('13.','123四'.isnumeric())          #True
print('14.','ⅠⅡⅢ'.isnumeric())          #True
  1. isalnum() 判断指定的字符串是否全部由字母和数字组成
print('15.','abc1'.isalnum())          #True
print('16.','张三123'.isalnum())          #True
print('17.','abc!'.isalnum())      #False

字符串的常用操作

1.字符串替换 replace():(被替换,替换,替换次数)

s='hello,Python'
print(s.replace('Python','Java'))
s1='hello,Python,Python,Python,Python'
print(s1.replace('Python','Java',2))           #两次替换次数

2.字符串合并 join():将列表和元组中的字符串合并成一个字符串

lst=['hello','java','Python']
print('|'.join(lst))     #hello|java|Python
print(''.join(lst))     #hellojavaPython

t=('hello','java','Python')
print(' '.join(t))           #hello java Python

print('*'.join('Python'))          #P*y*t*h*o*n

3.字符串的比较操作

❀比较符 > < =

print('apple'>'app')        #True
print('apple'>'banana')     #比较的asscii码
print(ord('a'),ord('b'))   #97,98
print(ord('孙'))      #23385

print(chr(97),chr(98))   #a,b
print(chr(23385))

❃== 和 is 的区别
==比较的是value
is 比较的是id是否相等

a=b='Python'
c='Python'
print(a==b)      #True
print(b==c)      #True    只比较大小

print(a is b)     #True
print(a is c)     #True      还比较内存地址,驻留机制

4字符串的切片操作
字符串时不可变类型,不具备增删改操作,切片将产生新的对象。
图片说明

s='hello,Python'
s1=s[:5]       #没有指定起始位置,从0开始
s2=s[6:]      #没有指定结束位置,直到结束为止
s3='!'

newstr=s1+s3+s2

print(id(s))
print(s1,id(s1))
print(s2,id(s2))
print(id(s3))
print(newstr,id(newstr))

完整的写法:切片[start:end:step]

s='hello,Python'
print(s[1:5:1])         #ello,从1开始到5结束,不包括5
print(s[::2])             #hloPto
print(s[::-1])         #步长为负数,默认从最后一位开始截取
print(s[-6::1])       #Python

格式化字符串

例如:
'''兹证明xxx,身份证号xxxxxx,现居家庭住址xxxx,为我公司员工,工作地址xxxx'''
这样的格式文件,就需要使用格式化字符串操作,有三种常用的方法,不会占用大量的内存,如果使用+做字符串拼接,就会占用大量的内存。

1.梦回C语言 %作为占位符

name='张三'
age=20
print('我叫%s,今年%d岁了' % (name,age))

2.{}作为占位符

name='张三'
age=20
print('我叫{0},今年{1}岁'.format(name,age))#0和1作为索引

3.f-string

name='张三'
age=20
print(f'我叫{name},今年{age}岁')

表示精度和宽度

1.使用%

print('%10d'%99)      #10表示的是宽度,向右对齐
print('hellohello')     #用于和前面的对比
print('%f'%3.1415926)         #3.141593
print('%.3f'%3.1415926)       #保留3位小数  3.142
print('%10.3f'%3.1415926)     #同时表示宽度和精度

2.使用{}.format()

print('{0:.3}'.format(3.1415926))    #0表示占位符  3表示的是一共有三位数  结果:3.14
print('{:.3f}'.format(3.1415926))        #.3f  表示3位小数    结果:3.142
print('{:10.3f}'.format(3.1415926))       #一共十位,有三位小数

字符串的编码转换

编码 (爬虫的时候用得到),不同的编码方式,字符串占用的字节不一样

s='天涯共此时'
print(s.encode(encoding='GBK'))       #一个中文占两个字节
print(s.encode(encoding='UTF-8'))     #在这种编码格式中,一个中文占3个字节

解码 (格式要和编码格式相同
byte代表的就是一个二进制数据

s='天涯共此时'
byte=s.encode(encoding='GBK')        #编码
print(byte.decode(encoding='GBK'))    #解码