格式化输出(点点滴滴)

一.字符串格式化输出方法一:

name = "tom"
age = 18
print("名字是%s,年龄是%s" % (name, age))  # (name,age)只能是带括号的元组,不能是列表
# 名字是tom,年龄是18
# %d -----十进制
name = "tom"
age = 18
print("名字是%s,年龄是%d" % (name, age))
# 名字是tom,年龄是18
# %f 转换成浮点数 (小数部分自然截断)   默认6位小数
name = "tom"
age = 18
print("名字是%s,年龄是%f" % (name, age))
# 名字是tom,年龄是18.000000
# %x  转换成16进制
# 指定长度打印  -----数值和字符串是一样的

# 1. %5   右对齐,不足的话左边补空格
name = "tom"
age = 18
print("名字是%s,年龄是%5d" % (name, age))
# 名字是tom,年龄是   18
# 2. %-5  左对齐,不足的话右边补空格
name = "tom"
age = 18
print("名字是%s,年龄是%-5d" % (name, age))
# 名字是tom,年龄是18
# 3. 补0    %05d
name = "tom"
age = 18
print("名字是%s,年龄是%05d" % (name, age))
# 名字是tom,年龄是00018
# 小数---float
# 1.默认是6位
print("%f" %3.14)
# 3.140000
# 2.指定保留小数位数 ---%.3f-----进行了四舍五入
print("%.3f" %3.1415926)
# 3.142
# 3.保留整数位
print("%8.3f" % 3.1415926)
#    3.142(总共8位,前面有空格,包括小数点;且小数点后面3位)
# 4.保留整数位,补0
print("%08.3f" % 3.1415926)
# 0003.142(总共8位,前面有空格,包括小数点;且小数点后面3位)
# 二.字符串格式化输出方法二:   format()----固定的{}
# 1.顺序填坑: 可以有元素多,不能有元素少
name = "tom"
age = 18
print("名字是{},年龄是{}" .format(name,age))
# 名字是tom,年龄是18
# 2.下标填坑
name = "tom"
age = 18
print("名字是{1},年龄是{0}".format(age, name))
# 名字是tom,年龄是18
# 3.变量方法
print("名字是{name},年龄是{age}".format(age=18, name="tom"))
# 名字是tom,年龄是18
# 4.指定长度输出:(最好用第二种方法)
# 1.{:长度}
#     1.数值型:右对齐,左补齐
#     2.字符串:左对齐,右补齐
name = "tom"
age = 9
print("名字是{:5},年龄是{:5}".format(name, age))
# 名字是tom  ,年龄是    9
# 2.>   右对齐   (箭头朝哪边就是哪边对齐)
# 3.<   左对齐   (箭头朝哪边就是哪边对齐)
name = "tom"
age = 9
print("名字是{:>5},年龄是{:>5}".format(name, age))
# 名字是  tom,年龄是    9
# 4.^ 中间对齐(居中)
name = "tom"
age = 9
print("名字是{:^5},年龄是{:^5}".format(name, age))
# 名字是 tom ,年龄是  9
# 4.1 .^ 中间对齐(居中),空白的地方用*号补
name = "tom"
age = 9
print("名字是{:*^5},年龄是{:*^5}".format(name, age))
# 名字是*tom*,年龄是**9**
# 5.  数值补0,一般是左对齐补0,会改变值
# 6.  字符串本身带{},使用{{}}
# 三.python3.6以后 f""
name = "tom"
age = 9
print(f"名字是{name},年龄是{name}")
# 名字是tom,年龄是tom
# 四:转义符  \
print("name is \n tom")
# name is
#  tom
# 五:字符终端输入
# input()
#    1.有返回值,是str
#    2.如果对等到值进行算术-----int()

猜你喜欢

转载自blog.csdn.net/qq_37615098/article/details/82469384