x ='a'.encode('utf-8')print(x,type(x),x.decode())
y =ord('a')#ord()返回单个字符的unicode码(ASCII)print(y)print(type(y))print(chr(y),chr(y+1))#chr()返回unicode编码对应的字符
b'a' <class 'bytes'> a
97
<class 'int'>
a b
print(chr(ord("5")+4))print(ord(chr(97)))
9
97
微实例:将小写字母转化为大写字母,其余字符不变
plaincode =input('请输入明文:')for i in plaincode:if i.islower()==True:print(chr(ord(i)-32),end =' ')else:print(i,end =' ')
print('{0:.3f}'.format(1/3))#没有小数点则保留6位print('{0:%}'.format(3.5))#格式化为百分数print("The number {0:,} in hex is: {0:#x}, in oct is {0:o}".format(55))#‘#’的作用为添加进制前缀
0.333
350.000000%
The number 55 in hex is: 0x37, in oct is 67
print('My name is {name}, my gender is {gender}, my age is {age}.'.format(age =18, name ='XZP', gender ='male'))
My name is XZP, my gender is male, my age is 18.
position =(5,8,13)print("X:{0[0]};Y:{0[1]};Z:{0[2]}".format(position))#使用元组的同时格式化多个值
X:5;Y:8;Z:13
示例
显示一个数n的二进制,八进制,十进制,十六进制
n =int(input('a number:'))print('二进制:{0:b}, 八进制:{0:o}, 十进制:{0:d}, 十六进制:{0:x}'.format(n))
a number:16
二进制:10000, 八进制:20, 十进制:16, 十六进制:10
从键盘输入一个正整数n,然后输入n个数字,对这n个数字求和并显示结果。
n =int(input("输入一个正整数:"))
t =0for i inrange(1,n+1):
x =int(input("请输入第{}个数:".format(i)))
t = t + x
print("数字的总和是:{}".format(t))