python学习笔记_字符串与编码
1.ord() 得到字符的数字编码,类似于C语言中的取ASCII码操作
chr() 将编码转换为对应字符
2.x='ABC' x指向字符串ABC,编码方式未指定
x=b'ABC' 字符串前面加b,表示此字符串中的每一个字符都用一个字节来编码
bytes数据用b做前缀,后面跟单引号或双引号
3.encode() 将str编码转换为指定bytes
print('ABC'.encode('utf-8'))
decode() 将bytes编码转换为str
print(b'ABC'.decode('utf-8'))
4.len() 内部为str为测量str中字符数量
内部为bytes数据,为测量bytes数据中的字节数
5.格式化输出,跟C语言类似,Python中使用的为%?对应替换str或者数字等。常见的占位符
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数
ex:
print('My name is %s,my age is %d'%('Elecyang',25))
输出:
My name is Elecyang,my age is 25
输出也有格式设置
%2d 输出的数字占两位
%02d 输出的数字占两位,不够的前面补0
%.2f 输出的浮点数保留小数点后2位
%%表示一个%(转义)
格式化输出函数
format()函数
print('{0}{1}'.format('1','1'))
print('{name} is {age}'.format(name='ZLY',age='25'))
f-string格式化输出方法
r = 2.5
s = 3.14 * r ** 2
print(f'The area of a circle with radius {r} is {s:.2f}')

浙公网安备 33010602011771号