字串格式化

2022-04-02 12:25:23 字數 1826 閱讀 1956

"""

字串格式化

"""msg = "i am" + " cql " + " abc" # 效率低,開闢記憶體空間大

print(msg)

# %s 可以接收一切

print("i am %s, %s" % ("aaa", [1 ,2]))

print("i am %s, %s" % ("aaa", 11))

print("i am %s, %s" % ("aaa", "aa"))

print("i am %s, %s" % ("aaa", (1, 2)))

# %d只能接收int型別

print("i am %s, %d" % ("aaa", 12))

# %f

print("i am %s, %f" % ("aaa", 12.0)) # i am aaa, 12.000000 預設顯示6位小數

print("i am %s, %.2f" % ("aaa", 12.0)) # i am aaa, 12.00 只顯示2位小數%.2f

print("i am %s, %.2f%%" % ("aaa", 12.0)) # i am aaa, 12.00%, %% 列印%

# format 字典形式

print("i am %(name)s age %(age)d" % ) # i am cql age 12

print("i am %(pp).2f" % ) # i am 19.89

# 寬度

print("i am %+20s" % "cql") # i am cql

# 按指定字元分隔組合顯示

print("root", "***", 0, 0, sep=":") # root:***:0:0

format

tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')

tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])

tpl = "i am , age , really ".format("seven", 18)

tpl = "i am , age , really ".format(*["seven", 18])

tpl = "i am , age , really ".format(name="seven", age=18)

tpl = "i am , age , really ".format(**)

tpl = "i am , age , really ".format([1, 2, 3], [11, 22, 33])

tpl = "i am , age , money ".format("seven", 18, 88888.1)

tpl = "i am , age ".format(*["seven", 18])

tpl = "i am , age ".format(name="seven", age=18)

tpl = "i am , age ".format(**)

tpl = "numbers: ,,,,, ".format(15, 15, 15, 15, 15, 15.87623, 2)

print(tpl)

tpl = "numbers: ,,,,, ".format(15, 15, 15, 15, 15, 15.87623, 2)

tpl = "numbers: ,,,,, ".format(15)

tpl = "numbers: ,,,,, ".format(num=15)

字串格式化

sprintf snprintf snprintf std stringstream std strstream boost lexical cast boost format cstring format 1 sprintf 使用 sprintf 不安全,輕則破壞資料的準確性,重則程式崩潰。請看下...

格式化字串

通常在使用字串的時候,會對字串進行格式化,然後輸出或呼叫 一般我們使用替換標記對字串進行格式化 string str1 string.format add is 1,2,3 而且在c 中的替換標記可以以任意順序和次數出現在格式化字串中,但替換值是按順序排的,而且替換標記不能超出索引範圍 string...

字串格式化

例如 string s hello map.put target world string res format s,map 有什麼用呢?比如在some.properties中配置模板字串,但是如果用 這種方式,在配置了spring讀取properties注入變數的時候,這個變數就找不到會報錯。這個...