Python基础语法(七)

一、Python部分

内容介绍

1、字符串的驻留机制

2、字符串的常用操作

3、字符串的比较

4、字符串的切片操作

5、格式化字符串

6、字符串的编码转换

1、字符串的驻留机制

a='Python'
b="Python"
c='''Python'''
print(a,id(a))#Python 2054548967216
print(b,id(b))#Python 2054548967216
print(c,id(c))#Python 2054548967216

2、字符串的常用操作

a='Python%Python'
print(a.index('th'))  #2
print(a.rindex('th'))#9
print(a.find('th'))#2
print(a.rfind('th'))#9

a='python'
s=a.upper()     #转成大写后会产生新的字符串
print(a.upper())
print(s)

a='python'
print(a.center(12,'*'))

a='Python hello world'
lst=a.split()
print(lst)      #['Python', 'hello', 'world']
s='Python&hello&world'
print(s.split(sep='&'))#['Python', 'hello', 'world']
print(s.split(sep='&',maxsplit=1))#['Python', 'hello&world']

a='Python,hello,world'
print(a.isidentifier())
print(a.isspace())

a='Python,hello,world'
s=a.replace('Python','JAVA')
print(s)
a1='Python,Python,Python,hello,world'
s1=a1.replace('Python','JAVA',2)
print(s1)

lst = ['Python','hello','world']
print(' '.join(lst))

3、字符串的比较

a='Python'
b='chenchen'
print(a>b)
print(ord('P'),ord('c'))
print(chr(1),chr(80))

4、字符串的切片操作

5、格式化字符串

#%占位符
name='张三'
age=20
print('我叫%s,今年%d岁' % (name,age))

#{}占位符
print('我叫{0},今年{1}岁'.format(name,age))

#f-string
print(f'我叫{name},今年{age}岁')



print('%10d' % 99)  #10标识宽度
print('%.3f' % 3.1415926)   #保留小数点后位数
print('%10.3f' % 3.1415926) #10标识宽度,保留小数点后位数



print('{0:.3}'.format(3.1415926))   #.3标识一共三位数
print('{0:.3f}'.format(3.1415926))  #.3f标识三位小数
print('{0:10.3f}'.format(3.1415926))#10标识宽度,保留小数点后位数

6、字符串的编码转换

#编码
s='我要开始编码'
print(s.encode(encoding='GBK'))
print(s.encode(encoding='UTF-8'))

#解码
byte=s.encode(encoding='GBK')
print(byte.decode(encoding='GBK'))
byte1=s.encode(encoding='UTF-8')
print(byte1.decode(encoding='UTF-8'))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值