Python中格式化輸出字串使用format()函數用法

來源:互聯網
上載者:User
Python中格式化輸出字串使用format()函數, 字串即類, 可以使用方法;

Python是完全物件導向的語言, 任何東西都是對象;

字串的參數使用{NUM}進行表示,0, 表示第一個參數,1, 表示第二個參數, 以後順次遞加;

使用":", 指定代表元素需要的操作, 如":.3"小數點三位, ":8"佔8個字元空間等;

還可以添加特定的字母, 如:

'b' - 二進位. 將數字以2為基數進行輸出.

'c' - 字元. 在列印之前將整數轉換成對應的Unicode字串.

'd' - 十進位整數. 將數字以10為基數進行輸出.

'o' - 八進位. 將數字以8為基數進行輸出.

'x' - 十六進位. 將數字以16為基數進行輸出, 9以上的位元用小寫字母.

'e' - 冪符號. 用科學計數法列印數字, 用'e'表示冪.

'g' - 一般格式. 將數值以fixed-point格式輸出. 當數值特別大的時候, 用冪形式列印.

'n' - 數字. 當值為整數時和'd'相同, 值為浮點數時和'g'相同. 不同的是它會根據地區設定插入數字分隔字元.

'%' - 百分數. 將數值乘以100然後以fixed-point('f')格式列印, 值後面會有一個百分比符號.

數字(0, 1, ...)即代表format()裡面的元素, 所以可以使用"."調用元素的方法;

# -*- coding: utf-8 -*-  #====================#File: abop.py#Author: Wendy#Date: #====================  #eclipse pydev, python3.3  age = 25name = 'Caroline'  print('{0} is {1} years old. '.format(name, age)) #輸出參數print('{0} is a girl. '.format(name))print('{0:.3} is a decimal. '.format(1/3)) #小數點後三位print('{0:_^11} is a 11 length. '.format(name)) #使用_補齊空位print('{first} is as {second}. '.format(first=name, second='Wendy')) #別名替換print('My name is {0.name}'.format(open('out.txt', 'w'))) #調用方法print('My name is {0:8}.'.format('Fred')) #指定寬度

輸出:

Caroline is 25 years old. Caroline is a girl. 0.333 is a decimal. _Caroline is a 11 length. Caroline is as Wendy. My name is out.txtMy name is Fred.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.