Python中关于字符串的操作

#字符串驻留机制
a=‘Python,Python’
b=“Python”
c=’’‘Python’’’
print(a is b)
c=‘abc ′ d = " a b c ' d="abc d="abc"
#判断字符串内存地址是否相同
print(a is b)
#返回字符第一次出现的索引,若不存在index会报错,find会返回-1
print(a.index(‘on’))
print(a.find(‘on’))
#返回字符最后一次出现的索引,若不存在rindex会报错,rfind会返回-1
print(a.rindex(‘on’))
print(a.rfind(‘on’))
print(’-----------------------------------------’)
#字符串的大小写转换
#字符串大写转换

i=‘hello,world’
print(i.upper())
#字符串小写转换
j=‘HELLO,WORLD’
print(j.lower())
#大写转小写,小写转大写
k=‘hello,WORLD’
print(k.swapcase())
#第一个字符串转大写其余字符串转小写
print(k.capitalize())
#每个单词第一个字母转为大写,其余字母转为小写
print(i.title())
#字符串常用的对齐操作
a=‘hello,python’
#字符串居中对齐
print(a.center(20,’#’))
print(a.center(20))
#字符串左对齐
print(a.ljust(20,’@’))
print(a.ljust(10))
#字符串右对齐
print(a.rjust(20,’*’))
print(a.rjust(20))
print(a.zfill(20))
print(’-813’.zfill(8))
#字符串的分割操作
s=‘hello world python’
#左分割split
print(s.split())
s1=‘hello|word|python’
print(s1.split(sep=’|’))
#左分割并设置最大分割数
print(s1.split(sep=’|’,maxsplit=1))
#右分割rsplit
print(s1.rsplit(sep=’|’))
print(s1.rsplit(sep=’|’,maxsplit=1))
#字符串判断的相关操作
#判断指定字符串是不是合法字符

print(‘1.’,‘abc’.isidentifier())
print(‘2.’,‘1.’.isidentifier())
#判断指定字符串是否全部由空白字符组成
print(‘3.’,’ ‘.isspace())
#判断字符串是否全部由字母组成
print(‘4.’,‘abcd1’.isalpha())
print(‘5.’,‘wwwqwqw’.isalpha())
#判断字符串是否全部由十进制数字组成
print(‘6.’,‘123’.isdecimal())
#判断指定字符串是否全部由数字组成
print(‘7.’,‘2342’.isnumeric())
#判断指定字符串是否全部由字母和数字组成
print(‘8.’,‘w234’.isalnum())
#字符串的替换和合并
s=‘hello,python’
print(s.replace(‘python’,‘java’,1))
s2=[‘hello’,‘python’]
print(’’.join(s2))
print(’#’.join(‘python’))
print(’=’)
#字符串的比较操作
print(‘apple’>‘app’)
print(‘apple’>‘banana’)
print(ord(‘a’),ord(‘b’))
print(ord(‘黄’))
print(chr(40644))
a=123
b=123
c=b
#比较的是value,is比较的是id
print(a
b,a is b,a
b
c,id(a),id(b),id©)
print(’
[start🔚step]
’)
#字符串的切片操作
s=‘hello,python’
s1=s[:5]
print(s1)
s2=s[6:12:1]
print(s2)
s3=s[-6:]
print(s3)
s4=s[0:12:2]
print(s4)
**print('格式化字符串
’)**
name=‘张三’
age=20
print(‘我叫%s,今年%d岁’ %(name,age))
print(‘我叫{0},今年{1}岁’.format(name,age))
print(f’我叫{name},今年{age}岁’)
print(’%10d’ %99)
print(’%.3f’ % 3.141596747)
print(’%10.3f’ % 3.141596747)
print(’{0:.3}’.format(3.14159))
print(’{0:.3f}’.format(3.1415926))
print(’{0:10.3f}’.format(3.1415926))
*print(‘字符串的编码和解码=====’)*
s=‘我叫白小飞’
#编码
print(s.encode(encoding=‘GBK’))#GBK中一个中文占两个字节
print(s.encode(encoding=‘UTF-8’))#UTF-8中一个中文占三个字节
#解码
byte=s.encode(encoding=‘GBK’)
print(byte.decode(encoding=‘GBK’))
byte2=s.encode(encoding=‘UTF-8’)
print(byte2.decode(encoding=‘UTF-8’))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值