一、百分号%
print("格式化内容为 %s" % "hello")
str = "world"
print("格式化内容为 %s" % str)
template = "格式化内容为 %s"
print(template % "hello")
template = "格式化内容为 |%20s|"
print(template % "hello")
template = "格式化内容为 |%-20s|"
print(template % "hello")
template = "格式化内容为 |%+20s|"
print(template % "hello")
template = "格式化内容为 |%020s|"
print(template % "hello")
template = "格式化内容为 |%20.2s|"
print(template % "hello")
template = "格式化内容为 |%.2s|"
print(template % "hello")
template = "格式化内容为 |%20s|%12s|"
print(template % ("hello", "2020-07-08"))
print(template % ("hello world", "2020-07-08"))
template = "格式化内容为 |%d|"
print(template % 13)
template = "格式化内容为 |%x|"
print(template % 13)
template = "格式化内容为 |%o|"
print(template % 13)
template = "格式化内容为 |%10d|"
print(template % 13)
template = "格式化内容为 |%-10d|"
print(template % 13)
template = "格式化内容为 |%+10d|"
print(template % 13)
print(template % -13)
template = "格式化内容为 |%010d|"
print(template % 13)
print(template % -13)
template = "格式化内容为 |%f|"
print(template % 1234.5678)
template = "格式化内容为 |%.4f|"
print(template % 1234.5678)
template = "格式化内容为 |%.2f|"
print(template % 1234.5678)
print(template % 1234.5)
template = "格式化内容为 |%20.2f|"
print(template % 1234.5678)
template = "格式化内容为 |%-20.2f|"
print(template % 1234.5678)
template = "格式化内容为 |%+20.2f|"
print(template % 1234.5678)
template = "格式化内容为 |%020.2f|"
print(template % 1234.5678)
par = ("ycz", 18, "男")
template = "姓名%s 年龄%d 性别%s"
print(template % par)
template = "千分位 %s"
print(template % format(12345.6789, ","))
二、format
template = "格式化内容为{}"
print(template.format("hello"))
print("{} {} {}".format(1, 2, 3))
print("{0} {1} {0}".format(1, 2))
print("这个数字是{0} 是{0} 是{0}".format(13))
print("{:s}".format("hello"))
print("|{:20s}|".format("hello"))
print("|{:20.2s}|".format("hello"))
print("|{:>20.2s}|".format("hello"))
print("|{:^20.2s}|".format("hello"))
print("|{:+^20.2s}|".format("hello"))
print("|{:20d}|".format(13))
print("|{:0>20d}|".format(13))
print("|{:020d}|".format(13))
print("|{0:d}|{0:x}|{0:o}|{0:b}|".format(13))
print("|{0:d}|{0:#x}|{0:#o}|{0:#b}|".format(13))
print("|{:d}|{:d}|".format(13, -13))
print("|{:+d}|{:+d}|".format(13, -13))
print("|{:-d}|{:-d}|".format(13, -13))
print("|{: d}|{: d}|".format(13, -13))
print("{:f}".format(12345.6789))
print("{:.2f}".format(12345.6789))
print("{:20.2f}".format(12345.6789))
print("关键字传参{name} {age:0>10d} {sex}".format(name="ycz", age=18, sex="man"))
par = (1, 2, 3)
print("{0[0]} {0[1]} {0[2]}".format(par))
dic = {"x": 1, "y": 2, "z": 3}
print("{0[x]} {0[y]} {0[z]}".format(dic))
print("{:,.2f}元".format(12345.6789))
三、f-string
name = "ycz"
age = 18
salary = 19992.11
print("姓名{}年龄{}薪水{}".format(name, age, salary))
print(f"姓名{name.capitalize():.2s}年龄{age:010d}薪水{salary:,.2f}")