python中的printf:%號拼接字符串和format函數


在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM