Python之str操作,pythonstr

來源:互聯網
上載者:User

Python之str操作,pythonstr

1. str.format():使用“{}”預留位置格式化字串(預留位置中的索引號形式和索引值對形式可以混合使用)。

 1 >>> string = 'python{}, django{}, tornado{}'.format(2.7, 'web', 'tornado')  # 有多少個{}預留位置就有多少個值與其對應,按照順序“填”進字串中 2 >>> string 3 'python2.7, djangoweb, tornadotornado' 4 >>> string = 'python{}, django{}, tornado{}'.format(2.7, 'web') 5 Traceback (most recent call last): 6   File "<pyshell#6>", line 1, in <module> 7     string = 'python{}, django{}, tornado{}'.format(2.7, 'web') 8 IndexError: tuple index out of range 9 >>> string = 'python{0}, django{2}, tornado{1}'.format(2.7, 'web', 'tornado')  # 也可以指定“填”進去的值(從0開始,後面的值不一定都要用上,但是要保證指定的位置是有值的)10 >>> string11 'python2.7, djangotornado, tornadoweb'12 >>> string = 'python{py}, django{dja}, tornado{tor}'.format(tor='tornado', dja='web', py=2.7)  # 可以使用索引值對的形式賦值13 >>> string14 'python2.7, djangoweb, tornadotornado'15 >>> 

2. 使用“%”進行字串格式化。

格式化符號表
%c 轉為單字元
%r 轉為用repr()表達的字串
%s 轉為用str()表達的字串
%d或%i 轉為有符號的十進位整數
%u 轉為無符號的十進位整數
%o 轉為無符號的八進位整數
%x 轉為無符號的十六進位整數,十六進位字母用小寫表示
%X 轉為無符號的十六進位整數, 十六進位字母用大寫表示
%e 轉為科學計數法表達的浮點數,其中的e用小寫表示
%E 轉為科學計數法表達的浮點數,其中的E用大寫表示
%f或#F 轉為浮點數
%g 由Python根據數位大小自動判斷轉換為%e或%f
%G 由Python根據數位大小自動判斷轉換為%E或%F
%% 輸出“%”

 

 

 

 

 

 

 

 

 

 

 

 

 

 

輔助格式化符號表
* 定義寬度或小數點的精度
- 靠左對齊
+ 對正數輸出正值符號“+”
<sp> 數位大小不足m.n的要求時,用空格補位
# 在八位元前顯示0,在十六進位數前顯示0x或0X
0 數位大小不足m.n的要求時,用0補位
m.n m是顯示的最小總寬度,n是小數點後的位元(如果可用)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.