
驻留机制
仅保存一份相同且不可变字符串的方法。
- 字符串的驻留机制指:对相同的字符串只保留一份拷贝,后面创建相同字符串时,不会开辟新空间,而是把该字符串的地址赋给新创建的变量。
a='python'
b="python"
c='''python'''
print(a,id(a))
print(b,id(b))
print(c,id(c))
运行结果:
python 1531278147184
python 1531278147184
python 1531278147184
- 驻留机制的几种情况(交互模式)(win+R——>cmd)
- 字符串的长度为0,1
- 符合标识符的字符串(标识符:含字母数字下划线的字符串)
- 字符串只在编译时进行驻留,而非运行时
- [-5,256]之间的整数
- 强制让2个字符串指向同一地址
import sys
a='xxx'
b='xxx'
a=sys.intern(b)
a is b ##结果为True
- pycharm对字符串进行了优化处理
- 好处:避免频繁创建和销毁,可提升效率节约内存
在字符串拼接时建议使用 .join方法而非+
将列表/元组转为字符串类型:
','.join(要转换的变量)
,其中引号内的内容指字符串的连接符号
lst=[xxxxxx]
print(','.join(lst)):#x,x,x,x,x,x
t=(xxxxxx)
print(' '.join(t))#x x x x x x
字符串的常用操作
查询操作
与列表类似
- index():查找子串第一次出现的位置,若不存在抛出异常ValueError
- rindex():查找子串最后一次出现的位置,若不存在抛出异常ValueError
- find():查找子串第一次出现的位置,若不存在则返回-1
- rfind():查找子串最后一次出现的位置,若不存在则返回-1
s='helloworld,helloworld'
print(s.index('ld')) #8
print(s.find('ld')) #8
print(s.rindex('ld')) #19
print(s.rfind('ld')) #19
大小写转换操作
- upper():所有字符转为大写字母
- lower():所有字符转为小写字母
- swapcase():字符串中所有大写字母转成小写字母,小写字母转为大写字母
- capitalize():第一个字符转为大写,其他字符转为小写
- title():字符串中所有单词的第一个字符转为大写,其余转为小写
注意:转换操作后地址改变
s='hello python'
print(s,id(s)) #hello pyhton 1877257762736
s1=s.upper() #HELLO PYTHON 1877259552752
print(s1,id(s1))
s2=s1.lower() #hello python 1877259587312
print(s2,id(s2))
s3=s.capitalize() #Hello python 1877259587376
print(s3,id(s3))
s4=s.title() #Hello Python 1877259587440
print(s4,id(s4))
s5=s4.swapcase()
print(s5,id(s5)) #hELLO pYTHON 2143852716400
字符串内容对齐操作
- center():居中对齐,第一个参数指定宽度第二个参数指定填充符
第二个参数是可选的,默认为空格。若设置宽度小于实际宽度则返回原字符串 - ljust():左对齐,第一个参数指定宽度第二个参数指定填充符
第二个参数是可选的,默认为空格。若设置宽度小于实际宽度则返回原字符串 - rjust():右对齐,第一个参数指定宽度第二个参数指定填充符
第二个参数是可选的,默认为空格。若设置宽度小于实际宽度则返回原字符串
-zfill():右对齐,左边用0填充,只接受一个参数用于指定字符串的宽度。
若指定的宽度小于等于字符串长度,返回字符串本身。
s='hello,Python'
#print(s,id(s))
print(s.center(20,'*'))#居中对齐
print(s.ljust(20,'*'))#左对齐
print(s.ljust(10,'*'))#左对齐,指定宽度小于字符串宽度,返回原字符串
print(s.rjust(20))#右对齐,填充符默认为空格
print(s.zfill(20))#右对齐,用0进行填充
print('-2335'.zfill(10))
print('-2335'.rjust(10,'*'))
****hello,Python****
hello,Python********
hello,Python
hello,Python
00000000hello,Python
-000002335
*****-2335
劈分操作
- split():从字符串左边开始劈分,默认劈分字符为空格,返回值为一个列表
- rsplit():从字符串右边开始劈分,默认劈分字符为空格,返回值为一个列表
2个操作
通过参数sep指定劈分字符串的劈分符
通过参数maxsplit指定劈分字符串时的最大劈分数,在经过最大次劈分后,剩余的子字符串会单独作为一部分
注意:未指定最大劈分次数时,split 操作和rsplit操作效果相同
s='hello world Python'
lst=s.split()#未指定劈分符,默认为空格
print(lst,type(lst))
s1='hel|loworld|Pyt|hon'
print(s1.split(sep='|'))#指定劈分符为|
print(s1.split(sep='|',maxsplit=2))#最大劈分次数为2,剩余子串不再劈分
print(s.rsplit())
print(s1.rsplit())
print(s1.rsplit(sep='|',maxsplit=2))
运行结果:
['hello', 'world', 'Python'] <class 'list'>
['hel', 'loworld', 'Pyt', 'hon']
['hel', 'loworld', 'Pyt|hon']
['hello', 'world', 'Python']
['hel|loworld|Pyt|hon']
['hel|loworld', 'Pyt', 'hon']
判断操作
- isidentifier():判断指定字符串是否为合法的标识符
- isspace():判断指定字符串是否全部由空白字符组成(回车,换行,水平制表符)
- isalpha():判断指定字符串是否全部由全字母组成
- isdecimal():判断指定字符串是否全部由十进制的数字组成
- isnumeric():判断指定字符串是否全部由数字组成(数字包括罗马数字,中文数字等)
- isalnum():判断指定字符串是否由全部由字母和数字组成
s='hello,python'
print(s.isidentifier())#False,合法的标识符为数字、字母、下划线,“,”不是标识符
print('你好'.isidentifier())#True
print(' '.isspace()) #True
print('abc你好'.isalpha()) #True
print('abc1'.isalpha()) #False
print('123'.isdecimal()) #True
print('Ⅴ'.isdecimal()) #False
print('123'.isnumeric()) #True
print('123四'.isnumeric()) #True 中文数学也是数字
print('Ⅴ'.isnumeric()) #True 罗马数字也是数字
print('abca1你好四'.isalnum())#True
print('abc!'.isalnum())#False,!不是数字/字母
替换与合并操作
- 替换:replace():第一个参数指定被替换的子串;第二个参数指定替换子串的字符串:第三个参数指定最大替换次数,默认为全部替换
- 合并:join():将列表/元组中的字符串合并为1个字符串
s='hello,python'
print(s.replace('python','你好')) #hello,你好
s1='hello,python,python,python'
print(s1.replace('python','你好',2)) #hello,你好,你好,python
lst=['hello','你好','python','python']
print('|'.join(lst)) #hello|你好|python|python
print(' '.join(lst)) #hello 你好 python python
t=('hellp','python')
print(' '.join(t)) #hellp python
print('!'.join('python')) #p!y!t!h!o!n(字符串python作为字符串序列)
比较操作
- 运算符:>,<,>=,<=,==,!=
- 比较原则:先比较两个字符串中的第一个字符,若相等则比较下一个字符,一次进行下去直到2个字符串中的字符不相等。
- 比较原理:2个字符比较的是其原始值(原始值Unicode码),可调用函数ord()得到指定字符的原始值,chr()可获得原始值对应的字符
注:
Unicode为ASCII码的超集,ASCII为Unicode的前128项
==比较的是value,is 比较的是id
切片操作
与列表类似
s1=s[:5]#hello
s2=s[6:12]#world
s3='!'
print(s1+s3+s2)#hello!world
print('------------切片[start:end:step]-------------')
print(s[1:9:2])#el,y 从索引为1开始,索引为8结束,步长为2
print(s[::-1])#nohtyp,olleh 默认从字符串最后一位开始,字符串第一个结束,因为步长为-1
print(s[-6::1])#python 从索引-6开始,最后一位结束
字符串的格式化
按一定格式输出的字符串
- 使用%作为占位符
%s——字符串
%i或%d——整数
%f——浮点数 - 使用{}作占位符
- 使用f
注意: 可以指定宽度和精度
name='Alice'
age=20
print('我叫%s,今年%d岁' % (name,age))#我叫Alice,今年20岁
print('我叫{0},今年{1}岁.我真的叫{0}'.format(name,age))#我叫Alice,今年20岁.我真的叫Alice
print(f'我叫{name},今年{age}岁')#我叫Alice,今年20岁
print('%10d' % 99)#%d表示整数,10表示的是宽度为10
print('%f' % 3.1415926)#3.141593
print('%.3f' % 3.1415926)#3.142 .3表示保留3位小数,即精度为3
#同时表示宽度和精度
print('%10.3f' % 3.141926)# 3.142,宽度为10,保留3位小数
print('{0}'.format(3.1415926))#3.1415926
print('{0:.3}'.format(3.1415926))#3.14 这里.3表示一共保留3位数,0表示索引,即占位顺序
print('{0:10.3f}'.format(3.1415926))# 3.142 .3f表示保留3位小数,10表示宽度为10
编码转换
注意编码和解码的格式要相同
s='你好吗'
print(s.encode(encoding='GBK'))#在GBK这种编码格式中1个中文占2个字节
print(s.encode(encoding='UTF-8'))#在UTF-8中1个中文占3个字节
#解码
byte=s.encode(encoding='GBK')#编码
print(byte.decode(encoding='GBK'))#解码
byte1=s.encode(encoding='UTF-8')
print(byte1.decode(encoding='UTF-8'))
b'\xc4\xe3\xba\xc3\xc2\xf0'
b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97'
你好吗
你好吗