python字符串

本文详细介绍了Python字符串的驻留机制,包括长度为0或1的字符串、符合标识符的字符串以及[-5,256]之间的整数字符串的特性。此外,还探讨了字符串的常用操作,如查询、大小写转换、对齐、劈分、判断、替换和合并。同时,文章涉及字符串的比较、切片操作、编码转换等,并举例说明了字符串在内存中的表现。内容覆盖了字符串的基本操作和高级用法,对于理解Python字符串处理非常有帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串

字符串的驻留机制

#1.字符串的驻留机制
a='python'
b="python"
c='''python'''
#abc指向同一块空间
print(a,id(a))#python 2331968926512
print(b,id(b))#python 2331968926512
print(c,id(c))#python 2331968926512

接下来我们使用win+R cmd查看
驻留机制的几种情况

字符串的长度为0或1

>>> s1=' '
>>> s2=' '
>>> s1 is s2
True
>>> s1='%'
>>> s2='%'
>>> s1 is s2
True
>>> s1='abc%'
>>> s2='abc%'
>>> s1==s2
True
>>> s1 is s2
False
>>> id(s1)
2190447144432
>>> id(s2)
2190447145264

符合标识符的字符串


>>> s1='abcx'
>>> s2='abcx'
>>> s1 is s2
True
>>> id(s1)
2190447145328
>>> id(s2)
2190447145328

#·字符串只在编译时进行驻留,而非运行时


>>> a='abc'
>>> b='ab'+'c'
>>> c=''.join(['ab','c'])
>>> a is b
True
>>> a is c
False
>>> c
'abc'
>>> type(c)
<class 'str'>
>>> a
'abc'
>>> type(a)
<class 'str'>

[-5,256]之间的整数数字


>>> a=-5
>>> b=-5
>>> a is b
True
>>> a=-6
>>> b=-6
>>> a is b
False
>>> import sys
>>> a='abc%'
>>> b='abc%'
>>> a is b
False
>>> a=sys.intern(b)
>>> a is b
True
>>>

2.字符串的常用操作

字符串的查询操作


s='hello,hello'
print(s.index('lo'))#3
print(s.find('lo'))#3
print(s.rindex('lo'))#最后一次出现的位置9
print(s.rfind('lo'))#9

#print(s.index('k'))ValueError: substring not found
print(s.find('k'))#-1
#print(s.rindex('k'))#ValueError: substring not found
print(s.rfind('k'))#-1



字符串中大小写转换





s='hello.python'
a=s.upper()#转成大写之后,会产生一个新的字符串对象
print(a)#HELLO.PYTHON
print(a,id(a))#HELLO.PYTHON 2182702919600
print(s,id(s))#hello.python 2182701511088
#print(s.lower(),id(s.lower()))#hello.python 2210477936496
b=s.lower()#转换之后会产生一个新的字符串对象
print(b,id(b))#hello.python 1638325383280
print(s,id(s))#hello.python 1638319780656
print(b==s)#True
print(b is s)#False


s2='happy,DAY'
#swapcase()把字符串中大小写字母转换
print(s2.swapcase())#HAPPY,day
#title()把每个单词的第一个字符转换为大写,其余为小写
print(s2.title())#Happy,Day
#capitalize()把第一个字符转为大写其余为小写
print(s2.capitalize())#Happy,day



字符串对齐


s='hello,python'
print(s.center(20,'*'))#****hello,python****
"""左对齐"""
print(s.ljust(20,'*'))#hello,python********
print(s.ljust(10))#hello,python
print(s.ljust(20))#hello,python        <这里有空格

"""右对齐"""
print(s.rjust(20,'*'))
print(s.rjust(20))
print(s.rjust(10))
"""右对齐,使用0进行填充"""
print(s.zfill(20))
print(s.zfill(10))
print('-8910'.zfill(8))
'''

字符串劈分操作的方法


s='hello world Python'
lst=s.split()
print(lst)#['hello', 'world', 'Python']
s1='hello|world|Python'
print(s1.split('|'))
print(s1.split('|',maxsplit=1))
"""resplit()从右开始劈分"""
print(s.rsplit())#['hello', 'world', 'Python']
print(s1.rsplit('|'))#['hello', 'world', 'Python']
print(s1.rsplit('|',maxsplit=1))#['hello|world', 'Python']

字符串的判断


s='hello,python'
print('1.',s.isidentifier())#False不是合法的标识符
print('2.','hello'.isidentifier())#True是合法的标识符
print('3.','张三_'.isidentifier())#True是合法的标识符
print('4.','张三_123'.isidentifier())#True是合法的标识符
#isspace()判断指定的字符是否全部由空白字符组成
print('5.','\t'.isspace())#True
#isalpha()判断指定的子符串是否全部由字母组成

print('6.','abc'.isalpha())#True
print('7.','张三'.isalpha())#True
print('8.','张三1'.isalpha())#False
#isdecimal判断指定的字符串是否全部由十进制数字组成
print('9.','123'.isdecimal())#True
print('10.','123四'.isdecimal())#False
print('11.','ⅠⅡⅢ'.isdecimal())#False
#isnumeric()判断指定的子符是否全部由数字组成
print('12.','123'.isnumeric())#True
print('13.','123四'.isnumeric())#True
print('14.','ⅠⅡⅢ'.isnumeric())#True

#isalnum()判断指定字符串是否全部由字母和数字组成
print('15.','123'.isalnum())#True
print('16.','123四'.isalnum())#True
print('17.','ⅠⅡⅢ'.isalnum())#True



replace()字符串替换


s='hello,python'
print(s.replace('python','Java'))#hello,Java
s1='hello,Python,Python,python'
print(s1.replace('Python','Jave',2))#hello,Jave,Jave,python

join()字符串的合并

lst=['hello','java','Python']
print('|'.join(lst))#hello|java|Python
print(' '.join(lst))#hello java Python
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')#False
print(ord('a'),ord('b'))#asscul
print(ord('哈'))#21704
print(chr(97),chr(98))#a b
print(chr(21704))#哈

'''== 与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
print(id(a))#2297656203760
print(id(b))#2297656203760
print(id(c))#2297656203760

4.字符串的切片操作


s='hello,Python'
s1=s[:5]#由于没有指定起始位置,所以从0开始切
s2=s[6:]#由于没有指定结束位置,所以切到最后一个
s3='!'
newstr=s1+s3+s2
print(s1)#hello
print(s2)#Python
print(newstr)#hello!Python
print('------------')
print(id(s))#2143419626352
print(id(s1))#2143425236656
print(id(s2))#2143425236720
print(id(s3))#2143425151088
print(id(newstr))#2143425256624
print('----切片[star:end:step]----')
print(s[1:5:1])#ello从1开始截到5(不包括5)步长为1
print(s[::2])#hloPto
print(s[::-1])#nohtyP,olleh从字符串最后一个元素开始,到第一个
print(s[-6::1])#Python


#5.格式化字符串

name='张三'
age=20
print('我叫%s,今年%d岁'%(name,age))#我叫张三,今年20岁
print('我叫{0},今年{1}岁'.format(name,age))
print(f'我叫{name},今年{age}岁')#我叫张三,今年20岁

print('%10d'%99)           #        99
print('%.3f'%3.141592653)  #3.142
print('0123456789')        #0123456789
print('%10.3f'%3.14159265)#宽度10,小数点后三位
print('{0:.3}'.format(3.14159265))   #3.14
print('{0:.3f}'.format(3.14159265))  #3.142
print('{0:10.3f}'.format(3.14159265))#     3.142

6.字符串的编码转换

s='床前明月光'

print(s.encode(encoding='GBK'))#在GBK这种编码中一个中文两个字节
#b'\xb4\xb2\xc7\xb0\xc3\xf7\xd4\xc2\xb9\xe2'
print(s.encode(encoding='UTF-8'))#在UTF-8这种编辑格式中,一个中文占三个字节
#b'\xe5\xba\x8a\xe5\x89\x8d\xe6\x98\x8e\xe6\x9c\x88\xe5\x85\x89'

#解码
#byte代表一个二进制数据(字节类型的数据)
byte=s.encode(encoding='GBK')
print(byte.decode(encoding='GBK'))#床前明月光

byte=s.encode(encoding='UTF-8')
print(byte.decode(encoding='UTF-8'))#床前明月光
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

` starmultiple `

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值