Python_字符串格式化

时间:2023-03-09 10:04:43
Python_字符串格式化
 #冒泡排序
array = [1,2,3,6,5,4]
for i in range(len(array)):
for j in range(i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
print(array)
#字符串格式化用法
x=123
so="%o"%x #8进制
print(so)
sh = "%x"%x #16进制
print(sh)
se='%e'%x
print(se)
print('%s'%65) #等价于str()
print('%s'%65333)
print('%d,%c'%(65,65)) #使用元组对字符串进行格式化,按位置进行对应
print(int('')) #可以使用int()函数将合法的数字字符串转化为整数
print('%s'%[1,2,3])
print(str([1,2,3])) #可以使用str()函数将任意类型数据转换为字符串
print(str((1,2,3)))
print(str({'A':65,'B':66})) #使用format()方法进行格式化,该法官法更加灵活,不仅可以使用位置进行格式化,还支持使用与位置无关的参数名来进行格式化,并且支持
#序列解包格式化字符串,为程序员提供非常大的方便
print('{0:.3f}'.format(1/3)) #保留3位小数
# 0.333
print("The number {0:,} in hex is: {0:#x},i oct is {0:#o}".format(55))
# The number 55 in hex is: 0x37,i oct is 0o67
print('The number {0:,} in hex is: {0:x},the number {1} inn oct is {1:o}'.format(555,55))
#The number 555 in hex is: 22b,the number 55 inn oct is 67
print('THe number {1} in hex is: {1:#x},the number {0} in oct is {0:#o}'.format(5555,55))
# THe number 55 in hex is: 0x37,the number 5555 in oct is 0o12663
print('My name is {name},my age is {age},and my QQ is {qq}'.format(name='zWrite',qq='122668xx',age=25))
# My name is zWrite,my age is 25,and my QQ is 122668xx
position =(5,6,12)
print('X:{0[0]};Y:{0[1]};Z:{0[2]}'.format(position)) #使用元组同时格式化多值
# X:5;Y:6;Z:12
weather = [('Monday','rain'),('Tuesday','sunny'),('Wednessday','sunny'),('Thursday','rain'),('Friday','cloudy')]
formatter='Weather of "{0[0]}" is "{0[1]}"'.format
for item in map(formatter,weather):
print(item)
# Weather of "Monday" is "rain"
# Weather of "Tuesday" is "sunny"
# Weather of "Wednessday" is "sunny"
# Weather of "Thursday" is "rain"
# Weather of "Friday" is "cloudy"
from string import Template
t = Template('My name is ${name},and is ${age} years old.') #创建模版
d = {'name':'zWrite','age':39}
t.substitute(d) #替换
print(t)
# <string.Template object at 0x101389198>
tt = Template('My name is $name,and is $age years old.')
tt.substitute(d)
print(tt)
# <string.Template object at 0x101389588>