python字符串格式化方法%s和format函數


1.%s方法

一個例子

print("my name is %s and i am %d years old" %("xiaoming",18)

輸出結果:my  name is xiaoming and i am 18 years old

而且也可以用字典的形式進行表示:

print("my name is %(name)s and i am %(year)d years old" %{"year":18,"name":"xiaoming"}

下面是常用字符格式
%% 百分號標記 #就是輸出一個%

%c 字符及其ASCII碼

%s 字符串

%d 有符號整數(十進制)

%u 無符號整數(十進制)

%o 無符號整數(八進制)

%x 無符號整數(十六進制)

%X 無符號整數(十六進制大寫字符)

%e 浮點數字(科學計數法)

%E 浮點數字(科學計數法,用E代替e)

%f 浮點數字(用小數點符號)

%g 浮點數字(根據值的大小采用%e或%f)

%G 浮點數字(類似於%g)

%p 指針(用十六進制打印值的內存地址)

%n 存儲輸出字符的數量放進參數列表的下一個變量中

2.format()函數

在python2.6開始,就新增加了一個字符串格式化字符的函數str.format(),此函數可以快速的處理各種字符串,增強了字符串格式化的功能。基本語法是使用{}和:來替代%。format函數可以接受不限各參數,位置可以不按照順序

>> "{} {}".format("hello","world")#設置指定位置,按默認順序
'hello world'


>>> "{0} {1}".format("hello", "world")  # 設置指定位置
'hello world'


>>> "{1} {0} {1}".format("hello", "world")  # 設置指定位置
'world hello world'
print("姓名:{name}, 年齡 {year}".format(name="xiaoming", year=18))

# 通過字典設置參數
site = {"name": "xiaoming", "year": 18}
print("網站名:{name}, 地址 {url}".format(**site))

# 通過列表索引設置參數
my_list = ['xiaoming',18]
print("姓名:{0[0]}, 年齡 {0[1]}".format(my_list))  # "0" 是可選的

 


免責聲明!

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



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