Python入門示例系列17 輸入與輸出( 格式化輸出 )


Python入門示例系列17 輸入與輸出

 

讀取鍵盤輸入(input)


Python 提供了 input() 內置函數從標准輸入(鍵盤)讀入一行文本,默認的標准輸入是鍵盤。返回結果是字符串

>>> astr = input("請輸入:");  ## input('提示的內容')
請輸入:123
>>> print(astr)
123

 如果從鍵盤輸入兩個數字,並求這兩個數字之和,該怎么寫程序呢?

a=input("請輸入一個數字 ")
b=input("請再輸入一個數字 ")
print("求和結果 ", eval(a)+eval(b)) # 為什么不是 a+b ?

 

eval(expression)
eval函數解析expression參數並將其評估為python表達式。換句話說,我們可以說這個函數解析了傳遞給它的表達式並在程序中運行python expression(code)。
為了評估基於字符串的表達式,Python的eval函數運行以下步驟:
    解析表達式
    編譯成字節碼
    將其評估為Python表達式
    返回評估結果

 

輸出

只想快速顯示變量進行調試,可以用 str() 函數把值轉化為字符串。

在Python 3.6之前,有兩種將Python表達式嵌入到字符串文本中進行格式化的主要方法:%-formattingstr.format()

從Python 3.6開始,f-string是格式化字符串的一種很好的新方法。與其他格式化方式相比,它們不僅更易讀,更簡潔,不易出錯,而且速度更快。

 

% 字符串(  "格式化字符串" % (輸出值) 

示例1:

name = "Eric"
"Hello, %s." % name

示例2:

name = "Eric"
age = 74
"Hello, %s. You are %s." % (name, age)

print('%x, %X' % (12, 15)) 

print('[%c]' % 97)

 

缺點:

使用幾個參數和更長的字符串,你的代碼將很快變得不太容易閱讀。不能正確顯示元組或字典。


 

str.format()  "格式化字符串".format(輸出值)

在Python 2.6中引入的。

該方法也用 { 和 } 標記替換變量的位置,雖然這種方法支持詳細的格式化指令,但需要提供格式化信息。

示例:

print("{0},{1},{2}".format(1,2,3))
print("{2},{1},{0}".format(1,2,3))
print("{1},{1},{1}".format(1,2,3))
print("{0:b},{1:x},{2:o}".format(1,12,16)) # b 二進制  x 十六進制 o 八進制

結果:

1,2,3
3,2,1
2,2,2
1,c,20

 

標准格式說明符 的一般形式如下:

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

各種對齊選項的含義如下:

選項

含意

'<'

強制字段在可用空間內左對齊(這是大多數對象的默認值)。

'>'

強制字段在可用空間內右對齊(這是數字的默認值)。

'^'

強制字段在可用空間內居中。

 
對齊文本以及指定寬度:

>>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' 

上面的代碼指定輸出字符串的寬度為30個字符。

sign 選項僅對數字類型有效,可以是以下之一:

選項

含意

'+'

表示標志應該用於正數和負數。

'-'

表示標志應僅用於負數(這是默認行為)。

 

width 是一個定義最小總字段寬度的十進制整數,包括任何前綴、分隔符和其他格式化字符。 如果未指定,則字段寬度將由內容確定。

precision 是一個十進制數字,表示對於以 'f' and 'F' 格式化的浮點數值要在小數點后顯示多少個數位,或者對於以 'g''G' 格式化的浮點數值要在小數點前后共顯示多少個數位。

'{:20.4f}'.format(123.456789)
'            123.4568'
'{:20.4F}'.format(123.456789)
'            123.4568'

 

type 確定了數據應如何呈現。

可用的字符串表示類型是:

類型

含意

's'

字符串格式。這是字符串的默認類型,可以省略。

示例

'{:30s}'.format("abcde")
'abcde                         '
'{:<30s}'.format("abcde")
'abcde                         '
'{:>30s}'.format("abcde")
'                         abcde'
'{:^30s}'.format("abcde")
'            abcde        

 

 

可用的整數表示類型是:

類型

含意

'b'

二進制格式。 輸出以 2 為基數的數字。

'c'

字符。在打印之前將整數轉換為相應的unicode字符。

'd'

十進制整數。 輸出以 10 為基數的數字。

'o'

八進制格式。 輸出以 8 為基數的數字。

'x'

十六進制格式。 輸出以 16 為基數的數字,使用小寫字母表示 9 以上的數碼。

'X'

十六進制格式。 輸出以 16 為基數的數字,使用大寫字母表示 9 以上的數碼。 在指定 '#' 的情況下,前綴 '0x' 也將被轉為大寫形式 '0X'

示例

'{:20b}'.format(111)
'             1101111'
'{:20d}'.format(111)
'                 111'
'{:20o}'.format(111)
'                 157'
'{:20x}'.format(111)
'                  6f'

 

floatDecimal 值的可用表示類型有:

類型

含意

'e'

科學計數法。 對於一個給定的精度 p,將數字格式化為以字母 'e' 分隔系數和指數的科學計數法形式。 系數在小數點之前有一位,之后有 p 位,總計 p + 1 個有效數位。 如未指定精度,則會對 float 采用小數點之后 6 位精度,而對 Decimal 則顯示所有系數位。 如果小數點之后沒有數位,則小數點也會被略去,除非使用了 # 選項。

'E'

科學計數法。 與 'e' 相似,不同之處在於它使用大寫字母 'E' 作為分隔字符。

'f'

定點表示法。 對於一個給定的精度 p,將數字格式化為在小數點之后恰好有 p 位的小數形式。 如未指定精度,則會對 float 采用小數點之后 6 位精度,而對 Decimal 則使用大到足夠顯示所有系數位的精度。 如果小數點之后沒有數位,則小數點也會被略去,除非使用了 # 選項。

'F'

定點表示。 與 'f' 相似,但會將 nan 轉為 NAN 並將 inf 轉為 INF

'%'

百分比。 將數字乘以 100 並顯示為定點 ('f') 格式,后面帶一個百分號。

 示例

'{:20.4e}'.format(123.456789)
'          1.2346e+02'
'{:20.4E}'.format(123.456789)
'          1.2346E+02'
'{:20.4f}'.format(123.456789)
'            123.4568'
'{:20.4F}'.format(123.456789)
'            123.4568'
'{:20.4%}'.format(123.456789)
'         12345.6789%'

 

 

 

格式示例
按位置訪問參數:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'


按名稱訪問參數:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} ## 字典
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord) ## 字典
'Coordinates: 37.24N, -115.81W'



訪問參數的項:

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'


替代 %x 和 %o 以及轉換基於不同進位制的值:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'



使用逗號作為千位分隔符:

>>> '{:,}'.format(1234567890)
'1,234,567,890'



表示為百分數:

>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'



使用特定類型的專屬格式化:

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

缺點:

當處理多個參數和更長的字符串時,str.format()仍然可能非常冗長。
 

 

f' '

f-string, f 字符串

 

使用 格式化字符串字面值 ,要在字符串開頭的引號(或三引號)前添加 f 或 F 。在這種字符串中,可以在 { 和 } 字符之間輸入引用的變量,或字面值的 Python 表達式。

示例

>>> name="Sam" >>> age=20 >>> f'{name} is {age} yeas old.' 'Sam is 20 yeas old.'

 可以將任何有效的Python表達式放入其中。

示例:

f"{2 * 37}"

 

name="Sam"
f"{name.lower()} is funny."

 

多行字符串:

name="Sam"
profession="teacher"
affiliation="XAUT"
message = (f"Hi {name}. " f"You are a {profession}. " f"You were in {affiliation}.") message

 

name="Sam"
profession="teacher"
affiliation="XAUT"

message = (f"Hi {name}. " "You are a {profession}. " "You were in {affiliation}.") message

 

format() 函數

示例

 

print ( format ( 57.467657, "10.2f" ) ) # f 表示浮點數
print ( format ( 12345678.923, "10.2f" ) ) #10表示寬度,2表示小數位數
print ( format ( 57.4, "10.2f" ) )
print ( format ( 57, "10.2f" ) )

 

 

print ( format ( 57.467657, "10.2e" ) ) # e表示科學計數法
print ( format ( 0.0033923, "10.2e" ) ) #10表示寬度,2表示小數位數
print ( format ( 57.4, "10.2e" ) )
print ( format ( 57, "10.2e" ) )

 

 

print ( format ( 0.53457, "10.2%" ) )# % 表示采用百分比形式
print ( format ( 0.0033923, "10.2%" ) ) #10表示寬度,2表示小數位數
print ( format ( 7.4, "10.2%" ) )
print ( format ( 57, "10.2%" ) )

 

 

print ( format ( "Welcome to Python", "20s" ) )# 20 表示寬度,s表示字符串
print ( format ( "Welcome to Python", "<20s" ) )  # <表示左對齊
print ( format ( "Welcome to Python", ">20s" ) )  # >表示右對齊
print ( format ( "Welcome to Python and Java", ">20s" ) )

 

 

REF

https://docs.python.org/zh-cn/3/tutorial/inputoutput.html

https://docs.python.org/zh-cn/3/library/string.html#formatspec

https://www.runoob.com/python3/python3-inputoutput.html

https://www.cnblogs.com/langqi250/p/10069342.html (f-string)


免責聲明!

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



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