在C語言中,我們使用printf("%s","hello")這種形式進行字符串的拼接
在python中,進行這樣的拼接有兩種實現方式,分別是%號拼接以及使用format函數,以下進行代碼演示
%號拼接字符串
在python中是用%號可以進行字符串的拼接,這個跟print函數是無關的。以下進行舉例
- 打印字符串
msg = "i am %s,my blogs is %s" % ("CodeScrew","www.cnblogs.com/codescrew") print(msg)
- 打印浮點數
msg = "i am %0.2f m" %1.785 print(msg) #打印結果為i am 1.78 m
其中%號后面的.2表示保留2位小數
- 打印百分比
msg = "it is %0.2f %%" % 99.852 print(msg) #打印結果為it is 99.85 %
- 使用鍵值對進行拼接
msg = "i am %(name)s.my age is %(age)d" % ({"name":"CodeScrew","age":23}) print(msg) #打印結果為i am CodeScrew.my age is 23
format函數處理字符串
除了%號進行拼接,還可以使用字符串類的format函數,以下列舉了常用的使用。
msg = "i am {},age is {}".format("CodeScrew",23) print(msg) #打印結果為i am CodeScrew,age is 23 msg = "i am {1},age is {0}".format("CodeScrew",23) print(msg) #打印結果為i am 23,age is CodeScrew msg = "i am {name},age is {age}".format(name="CodeScrew",age=23) print(msg) #打印結果為i am CodeScrew,age is 23 msg = "i am {name},age is {age}".format(**{"name":"CodeScrew","age":23}) print(msg) #打印結果為i am CodeScrew,age is 23 msg = "i am {:s},age is {:d}".format("CodeScrew",23) print(msg) #打印結果為i am CodeScrew,age is 23 msg = "i am {:s},age is {:d}".format(*["CodeScrew",23]) print(msg) #打印結果為i am CodeScrew,age is 23 msg = "Numbers:{:b},{:o},{:d},{:x},{:X}".format(15,15,15,15,15) print(msg) #打印結果為Numbers:1111,17,15,f,F