第一种: %
- 单个使用格式:“%s” % “test”
- 多个使用格式:“年份:%d,月份:%d, 日期:%d” % (2019,11,13)注:多个使用时,需按顺序填充,且格式内容需与符号对应(如%d取值str内容,则会报错)
- Python 字符串格式化符号:
# 顺序取值
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()
# 默认顺序
test = "年份:{},月份:{}".format(2019, 11)
print(test) # 年份:2019,月份:11
# 下标
test = "年份:{1},月份:{0}".format(2019, 11)
print(test) # 年份:11,月份:2019
# 下标(多次使用)
test = "年份:{1},月份:{0},年份:{1}".format(2019, 11)
print(test) # 年份:11,月份:2019,年份:11
# 变量
test = "年份:{year},月份:{month}".format(year=2019, month=11)
print(test) # 年份:2019,月份:11
第三种: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