第一種: %
單個使用格式:“%s” % “test”
-
多個使用格式:“年份:%d翘骂,月份:%d壁熄, 日期:%d” % (2019帚豪,11,13)
注:多個使用時草丧,需按順序填充狸臣,且格式內(nèi)容需與符號對應(如%d取值str內(nèi)容,則會報錯)
-
Python 字符串格式化符號:
符號 描述 %c 格式化字符及其ASCII碼 %s 格式化字符串 %d 格式化整數(shù) %u 格式化無符號整型 %o 格式化無符號八進制數(shù) %x 格式化無符號十六進制數(shù) %X 格式化無符號十六進制數(shù)(大寫) %f 格式化浮點數(shù)字昌执,可指定小數(shù)點后的精度 %e 用科學計數(shù)法格式化浮點數(shù) %E 作用同%e烛亦,用科學計數(shù)法格式化浮點數(shù) %g %f和%e的簡寫 %G %F 和 %E 的簡寫 %p 用十六進制數(shù)格式化變量的地址
# 順序取值
test = "年份:%s,月份:%s" % ("2019", "11")
print(test) # 年份:2019仙蚜,月份:11
test = "年份:%d此洲,月份:%d" % (2019, 11)
print(test) # 年份:2019,月份:11
# 格式字符串的參數(shù)順序填錯
test = "年份:%d委粉,月份:%d" % (11, 2019)
print(test) # 年份:11呜师,月份:2019
# 格式字符串的參數(shù)格式錯誤
test = "年份:%d,月份:%s" % ("2019", "11")
print(test)
# 報錯:TypeError: %d format: a number is required, not str
# 格式字符串的參數(shù)不足
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"
# 調用函數(shù)
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