41-常用的字符串格式化方法

print("%s is %s years old" % ('bob', 23))  # 常用
print("%s is %d years old" % ('bob', 23))  # 常用
print("%s is %d years old" % ('bob', 23.5))  # %d是整数 常用
print("%s is %f years old" % ('bob', 23.5))
print("%s is %5.2f years old" % ('bob', 23.5))  # %5.2f是宽度为5,2位小数
print("97 is %c" % 97)
print("11 is %#o" % 11)  # %#o表示有前缀的8进制
print("11 is %#x" % 11)
print("%10s%5s" % ('name', 'age'))  # %10s表示总宽度为10,右对齐, 常用
print("%10s%5s" % ('bob', 25))
print("%10s%5s" % ('alice', 23))
print("%-10s%-5s" % ('name', 'age'))  # %-10s表示左对齐, 常用
print("%-10s%-5s" % ('bob', 25))
print("%10d" % 123)
print("%010d" % 123)

print("{} is {} years old".format('bob', 25))
print("{1} is {0} years old".format(25, 'bob'))
print("{:<10}{:<8}".format('name', 'age'))


结果输出:


原文地址:https://www.cnblogs.com/hejianping/p/10882613.html