Python 格式化输出的3种方式

2019-11-14  本文已影响0人  R_zb

第一种: %

# 顺序取值
test = "年份:%s,月份:%s" % ("2019", "11")
print(test)     # 年份:2019,月份:11

test = "年份:%d,月份:%d" % (2019, 11)
print(test)     # 年份:2019,月份:11

# 格式字符串的参数顺序填错
test = "年份:%d,月份:%d" % (11, 2019)
print(test)     # 年份:11,月份:2019

# 格式字符串的参数格式错误
test = "年份:%d,月份:%s" % ("2019", "11")
print(test)
# 报错:TypeError: %d format: a number is required, not str

# 格式字符串的参数不足
test = "年份:%d,月份:%d" % (2019)
print(test)
# 报错:TypeError: not enough arguments for format string

第二种 :str.format()

第三种:f“ ”

year = 2019
month = 11
# 调用变量
print(f"年份:{year},月份:{month}")  # 年份:2019,月份:11
# 调用表达式
print(f"{2 * 100}")     # 200


def hi():
    return "hello"


# 调用函数
print(f"{hi()}")    # hello

# 调用列表下标
test = [2019, 11]
print(f"年份:{test[0]},月份:{test[1]}")     # 年份:2019,月份:11

# 调用字典
test = {"year": 2019, "month": 11}
print(f"年份:{test['year']},月份:{test['month']}")      # 年份:2019,月份:11

上一篇 下一篇

猜你喜欢

热点阅读