首页 > 代码库 > Python_字符串格式化

Python_字符串格式化

 1 #冒泡排序
 2 array = [1,2,3,6,5,4]
 3 for i in range(len(array)):
 4     for j in range(i):
 5         if array[j] > array[j + 1]:
 6             array[j], array[j + 1] = array[j + 1], array[j]
 7 print(array)
 8 #字符串格式化用法
 9 x=123
10 so="%o"%x   #8进制
11 print(so)
12 sh = "%x"%x #16进制
13 print(sh)
14 se=%e%x
15 print(se)
16 print(%s%65)  #等价于str()
17 print(%s%65333)
18 print(%d,%c%(65,65))  #使用元组对字符串进行格式化,按位置进行对应
19 print(int(120))   #可以使用int()函数将合法的数字字符串转化为整数
20 print(%s%[1,2,3])
21 print(str([1,2,3])) #可以使用str()函数将任意类型数据转换为字符串
22 print(str((1,2,3)))
23 print(str({A:65,B:66}))
24 
25 #使用format()方法进行格式化,该法官法更加灵活,不仅可以使用位置进行格式化,还支持使用与位置无关的参数名来进行格式化,并且支持
26 #序列解包格式化字符串,为程序员提供非常大的方便
27 print({0:.3f}.format(1/3))    #保留3位小数
28 # 0.333
29 print("The number {0:,} in hex is: {0:#x},i oct is {0:#o}".format(55))
30 # The number 55 in hex is: 0x37,i oct is 0o67
31 print(The number {0:,} in hex is: {0:x},the number {1} inn oct is {1:o}.format(555,55))
32 #The number 555 in hex is: 22b,the number 55 inn oct is 67
33 print(THe number {1} in hex is: {1:#x},the number {0} in oct is {0:#o}.format(5555,55))
34 # THe number 55 in hex is: 0x37,the number 5555 in oct is 0o12663
35 print(My name is {name},my age is {age},and my QQ is {qq}.format(name=zWrite,qq=122668xx,age=25))
36 # My name is zWrite,my age is 25,and my QQ is 122668xx
37 position =(5,6,12)
38 print(X:{0[0]};Y:{0[1]};Z:{0[2]}.format(position)) #使用元组同时格式化多值
39 # X:5;Y:6;Z:12
40 weather = [(Monday,rain),(Tuesday,sunny),(Wednessday,sunny),(Thursday,rain),(Friday,cloudy)]
41 formatter=Weather of "{0[0]}" is "{0[1]}".format
42 for item in map(formatter,weather):
43     print(item)
44 # Weather of "Monday" is "rain"
45 # Weather of "Tuesday" is "sunny"
46 # Weather of "Wednessday" is "sunny"
47 # Weather of "Thursday" is "rain"
48 # Weather of "Friday" is "cloudy"
49 from string import Template
50 t = Template(My name is ${name},and is ${age} years old.) #创建模版
51 d = {name:zWrite,age:39}
52 t.substitute(d) #替换
53 print(t)
54 # <string.Template object at 0x101389198>
55 tt = Template(My name is $name,and is $age years old.)
56 tt.substitute(d)
57 print(tt)
58 # <string.Template object at 0x101389588>

 

Python_字符串格式化