Python 基本数据类型之【格式化问题】

版权声明:转载请注明来源及作者,谢谢! https://blog.csdn.net/qq_42442369/article/details/84327860

content

  • **%**进行格式化
  • format进行格式化
  • f常量进行格式化
1. %进行格式化
# 有几个%占位,后面就跟着几个变量或者值,按照顺序对应
# 在python2的时候使用的比较多
# %s-----str(变量)
# %d  %f
a=1
b=2
c= 3
print("我有哪些数字%s和%s和%s" % (a,b,c))
# %ns :n占位  n如果是正数代表右对齐,如果是负数代表左对齐
print("字符串:%50s" % "hello")
print("字符串:%-20s" % "hello")
# 我有哪些数字1和2和3
# 字符串:                                             hello
# 字符串:hello
# # %.m :m代表取几位
print("字符串:%.2s" % "hello") # 左对齐 保留两位
print("字符串:%10.2s" % "hello")  # 正 右对齐 隔10个空 保留2位
# 字符串:he
# 字符串:        he
# %.mf  m代表保留的小数位数(掌握) 需要加f
# %.2f
print("%.2f" % 3.14159265358979)
print("%5.2f" % 3.14159265358979)
# 3.14
#  3.1
# 可以指定是否使用0补齐,需要在整数前面加0
print("%05.2f" % 3.14159265358979)
# 03.14
2. format进行格式化
# python2.6之后使用format进行格式3.5
# 格式 字符串{[参数名字/索引]:对齐方式 占位.保留位数 格式}.format(多个参数使用,分隔)
print("我有哪些数字{}和{}和{}".format(a,b,c))
# 花括号里面有什么
# <左对齐  >右对齐  ^中间对齐
print("{:<10}".format("hello"))
print("{:>10}".format("hello"))
print("{:^10}".format("hello"))
# hello     
#      hello
#   hello  
print("我有哪些数字{}和{}和{}".format(b,a,c))
a=1
b=2
c=3
print("我有哪些数字{x}和{y}和{z}".format(y=a,x=b,z=c))
# 我有哪些数字2和1和3
print("我有哪些数字{1}和{0}和{2}".format(a,b,c))  
# 我有哪些数字2和1和3
# 注意:是索引的打乱,第一个是从0开始
# 综合运用:
print("{:.2f}".format(3.14159))
print("{1:>10.2f}-{0:^20.3f}".format(3.14159,1.11112))
# 3.14
#       1.11-       3.142
3. f常量进行格式化
# 3.6之后可以f常量
a=1.2223
b=2
c=3
print(f"我有哪些数字{b}和{a}和{c}")
print(f"我有哪些数字{b}和{a:>10.2f}和{c}")

猜你喜欢

转载自blog.csdn.net/qq_42442369/article/details/84327860