1、输入
data = input("姓名:")
print("姓名:", data)
姓名:张三
姓名: 张三
2、格式化输出
规格化浮点数又称格式化输出,是指把一个浮点数按指定的格式进行转换。通常在报表统计展示、数据计算存储时需要格式化,常用的格式化函数有:format,cast等。
通常有两种方法:占位符输出和format格式化输出方法
(1)占位符输出
name = "张三"
age = 18
print("My name is %s, My age is %d" % (name, age))
My name is 张三, My age is 18
(2)f-string: formatted string literals, 格式化字符串常量
f/F 意义相同
格式化 {} 内容,不在 {} 内的照常展示输出
print(f"My name is {name}, My age is {age}")
(3)format输出
通过位置:
print("My name is {}, My age is {}".format(name, age))
通过关键字:
print("My name is {test}, My age is {age}".format(test=name, age=age))
通过元组下标顺序匹配:
print("My name is {0}, My age is {1}, My home is {2}".format(name, age, home))
例:输入月份显示正确的季节:
month = input("month:")
spring = ["3", "4", "5"]
summer = ["6", "7", "8"]
autom = ["9", "10", "11"]
winter = ["12", "1", "2"]
if month in spring:
print("%s 月是春天" %(month))
elif month in summer:
print("{} 月是夏天".format(month))
elif month in autom:
print("{month} 月是秋天".format(month=month))
elif month in winter:
print(f"{month} 月是冬天")
else:
print("请输入正确的年份")
格式化输出表格,常用于数据库输出:
^: 居中 <: 左对齐 >: 右对齐
print("{0:<5}{1:^12}{2:>19}".format("姓名", "联系方式", "地址"))
print("{0:<5}{1:^15}{2:>20}".format("张三", "15200000000", "陕西西安"))
print("{0:<5}{1:^15}{2:>20}".format("李四", "13800000000", "陕西咸阳"))
print("{0:<5}{1:^15}{2:>20}".format("王五", "13800000000", "陕西延安"))
姓名 联系方式 地址
张三 15200000000 陕西西安
李四 13800000000 陕西咸阳
王五 13800000000 陕西延安
{0:<5} "0"代表下标匹配后面的变量“姓名 "5" 代表变量字符占的个数
f-string 写法更加简便
print(f"{'姓名':<5}{'联系方式':^12}{'地址':>19}")
print(f"{'张三':<5}{'13800000000':^15}{'陕西西安':>20}")
print(f"{'李四':<5}{'13800000000':^15}{'陕西咸阳':>20}")
print(f"{'王五':<5}{'13800000000':^15}{'陕西延安':>20}")