Python 字符串格式化
"""
% 语法
"""
# %s 叫做占位符,格式化字符
print("格式化的内容是: %s" % 'hello world!')
s = 'world'
print("格式化的内容是: %s" % s)
"""
%[-][+][0][m][.n] 格式化字符 % 参数
其中, -:左对齐 +:右对齐 n:截取字符串
"""
template = "格式化的内容是: %s"
print(template % 'hello')
# m 占位宽度
template = "格式化的内容是: %10s"
print(template % 'hello')
# n 截取字符串长度
template = "格式化的内容是: %10.2s"
print(template % 'hello')
"""
%o 八进制 %d 十进制 %x 十六进制
"""
template = "格式化的内容是: %d"
print(template % 100)
template = "格式化的内容是: %o"
print(template % 100)
template = "格式化的内容是: %x"
print(template % 100)
template = "格式化的内容是: %f" # 默认有 6 位小数
print(template % 100)
template = "格式化的内容是: %.4f"
print(template % 100)
template = "格式化的内容是: %.4f" # 四舍五入
print(template % 100.34567)
"""
多个参数
"""
per = ("张三", 18, "男性")
template = "姓名: %s, 年龄: %d, 性别: %s"
print(template % per)
"""
金额千分位格式化 format
"""
template = "千分位格式化 : %s"
print(template % format(12345.6789, ','))
"""
多个一样的参数
"""
template = "这个数是: %d, 十六进制: %x, 八进制: %o"
print(template % (13, 13, 13))
"""
str.format() 方法格式化字符串
"""
template = "格式化的内容是: {}"
print(template.format("hello world"))
# index
print("{2} {1} {0}".format(1, 2, 3))
print("{0} {0} {0}".format(100))
# s 字符串
print("{:s}".format('hello'))
print("{:10s}".format('hello')) # 字符串默认左对齐
print("{:>10s}".format('hello')) # 右对齐
print("{:^10s}".format('hello')) # 中间对齐
print("{:10.2s}".format('hello')) # 截取
print("{:+^10s}".format('ab')) # 'ab'居中对其,空白区'+'填充
"""
十进制: d 十六进制: x 八进制: o 二进制: b
"""
print("{:10d}".format(13)) # 数值型默认右对齐
print("{:010d}".format(13))
print("{0:b} {0:o} {0:d} {0:x}".format(13))
print("{0:#b} {0:#o} {0:d} {0:#x}".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)) # 空格
"""
浮点数 f
"""
print('{:f}'.format(12345.6789))
print('{:.2f}'.format(12345.6789))
print('{:10.2f}'.format(12345.6789))
print('{:+10.2f}'.format(12345.6789))
"""
参数的传递
"""
print('{} {} {}'.format(1, 2, 3))
print('{2} {1} {0}'.format(1, 2, 3))
print('{0} {0} {0}'.format(1))
# 关键字传递参数
print("关键字传参: {name} {age} {gender}".format(name="harrytsz", age=20, gender="male"))
print("关键字传参: {name:^10.5s} {age:+>10d} {gender:<10s}".format(name="harrytsz", age=20, gender="male"))
# 元组形式传递参数
tup = (1, 2, 3)
print("tuple: {0[0]} {0[1]} {0[2]}".format(tup))
# 字典形式传递参数
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print("dict: {0[a]} {0[b]} {0[c]} {0[d]}".format(dic))
"""
千分位 金额
"""
print("{:,.2f}元".format(1234567890.6789))
"""
f-string python3.6版本新功能
f-string 可以看做是 format 方法的变形用法
"""
name = "harrytsz"
age = 20
salary = 1000000
print("Name: {}, Age: {}, Salary: {}".format(name, age, salary))
print(f"Name: {name}, Age: {age}, Salary: {salary}")
print(f"Name: {name:.5s}, Age: {age:010d}, Salary: {salary:,.2f}")
print(f"Name: {name.capitalize():.5s}, Age: {age:010d}, Salary: {salary:,.2f}") # Name 首字母大写