Python3.2中Print函數用法執行個體詳解

來源:互聯網
上載者:User

Python3.2中Print函數用法執行個體詳解

   本文執行個體講述了Python3.2中Print函數用法。分享給大家供大家參考。具體分析如下:

  1. 輸出字串

  ?

1

2

3

>>> strHello = 'Hello World'

>>> print (strHello)

Hello World

  2. 格式化輸出整數

  支援參數格式化,與C語言的printf類似

  ?

1

2

3

>>> strHello = "the length of (%s) is %d" %('Hello World',len('Hello World'))

>>> print (strHello)

the length of (Hello World) is 11

  3. 格式化輸出16進位,十進位,八進位整數

  #%x --- hex 十六進位

  #%d --- dec 十進位

  #%o --- oct 八進位

  ?

1

2

3

>>> nHex = 0xFF

>>> print("nHex = %x,nDec = %d,nOct = %o" %(nHex,nHex,nHex))

nHex = ff,nDec = 255,nOct = 377

  4.格式化輸出浮點數(float)

  ?

1

2

3

4

5

6

7

8

9

import math

>>> print('PI=%f'%math.pi)

PI=3.141593

>>> print ("PI = %10.3f" % math.pi)

PI = 3.142

>>> print ("PI = %-10.3f" % math.pi)

PI = 3.142

>>> print ("PI = %06d" % int(math.pi))

PI = 000003

  5. 格式化輸出浮點數(float)

  ?

1

2

3

4

5

6

7

8

>>> precise = 3

>>> print ("%.3s " % ("python"))

pyt

>>> precise = 4

>>> print ("%.*s" % (4,"python"))

pyth

>>> print ("%10.3s " % ("python"))

pyt

  6.輸出資料行表(List)

  輸出資料行表

  ?

1

2

3

>>> lst = [1,2,3,4,'python']

>>> print (lst)

[1, 2, 3, 4, 'python']

  輸出字典

  ?

1

2

3

>>> d = {1:'A',2:'B',3:'C',4:'D'}

>>> print(d)

{1: 'A', 2: 'B', 3: 'C', 4: 'D'}

  7. 自動換行

  print 會自動在行末加上斷行符號,如果不需斷行符號,只需在print語句的結尾添加一個逗號”,“,就可以改變它的行為。

  ?

1

2

3

4

5

6

7

8

9

>>> for i in range(0,6):

print (i,)

 

0

1

2

3

4

5

  或直接使用下面的函數進行輸出:

  ?

1

2

3

>>> import sys

>>> sys.stdout.write('Hello World')

Hello World

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

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