2024-06-20

輸出函數(shù)print用法(Python3):

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

這里是 print 函數(shù)的參數(shù)說明:

  • *objects:一個或多個對象,它們將被轉(zhuǎn)換為字符串(如果它們不是字符串的話)并輸出。多個對象之間用空格分隔,除非指定了 sep 參數(shù)
  • sep:用于分隔多個對象的字符串。默認(rèn)為空格 ' '
  • end:在最后一個對象之后附加的字符串。默認(rèn)為換行符 '\n'
  • file:一個文件對象(或類似的實現(xiàn)了 write(string) 方法的對象),用于指定輸出流。默認(rèn)為 sys.stdout,即標(biāo)準(zhǔn)輸出。
  • flush:一個布爾值,指定是否立即刷新輸出流。默認(rèn)為 False

print('jiujiang')
print("kejiangmin",47,True,"江西九江")
print("kejiangmin",47,True,"江西九江",sep='|')
# kejiangmin|47|True|江西九江

# 打開一個文件以寫入內(nèi)容,如果文件不存在則創(chuàng)建它  
with open('output.txt', 'w') as f: 
    # 使用 print 函數(shù)將內(nèi)容寫入文件  
    print('Hello, world!', file=f)  
# 此時,'output.txt' 文件將包含 "Hello, world!"

# 刷新輸出流(通常在需要立即看到輸出時使用,例如在網(wǎng)絡(luò)編程中)  
print("Hello, flush!", flush=True)

請注意,在大多數(shù)情況下,你不需要指定 file 和 flush 參數(shù),除非你打算將輸出重定向到文件或需要立即刷新輸出流。在大多數(shù)情況下,只使用 print 函數(shù)的基本形式就足夠了。


格式占位符的三種用法

  • 傳統(tǒng)模式

使用%操作符,你可以定義占位符來插入變量。占位符由%后跟類型說明符組成(如%s用于字符串,%d用于整數(shù),%f用于浮點數(shù)等)。

print("姓名:%s,年齡:%d,居住地:%s,卡余額:%.2f。"%("kejiangmin",47,"江西九江",3478.5))
# 姓名:kejiangmin,年齡:47,居住地:江西九江,卡余額:3478.50。
  • 占位符用法:
    %s:字符串(采用str()的顯示)
    %d、%i:十進制整數(shù)
    %f:浮點數(shù)
    %x、%X:十六進制整數(shù)(小寫和大寫)
    %o:八進制整數(shù)
    %e、%E:指數(shù)(基底寫為e或E)
    %g、%G:指數(shù)(e或E)或浮點數(shù)(根據(jù)顯示長度)
    %%:字符%,顯示百分號
  • 格式控制:
    可以在%和占位符之間加入數(shù)字或其他符號來表示更詳細(xì)的格式控制,例如%Ns進行右對齊,%-Ns進行左對齊,其中N是指定的寬度。
    可以用.Nf來指定浮點數(shù)的小數(shù)位數(shù),如%.2f保留小數(shù)點后兩位。
    可以用%+d來在正數(shù)前顯示+號。
    可以用%0Nd來指定當(dāng)整數(shù)的長度不足N時,用0填充。
  • str.format()用法---新模式

str.format() 是 Python 中字符串格式化的一個強大方法。它允許你使用占位符(例如 {})在你的字符串中,并通過 .format() 方法提供值來替換這些占位符。這種方法提供了比舊的 % 格式化方法更多的靈活性和功能。

{}中的格式說明:

"{:[[fill]align][sign][#][0][minimumwidth][group][.precision][type]}".format()
[[填充]對齊方式 ][正負(fù)號][#][0][寬度][分組選項][精度][類型]

填充和對齊方式:
使用<(左對齊)、>(右對齊)、^(居中對齊)以及一個可選的填充字符(默認(rèn)為空格)來控制,使用填充必須用對齊方式。
正負(fù)號:
使用+表示始終顯示正負(fù)號,-(或默認(rèn))表示僅在負(fù)數(shù)時顯示負(fù)號。
#
對于整數(shù)類型,#常用于指定進制前綴(如二進制0b、八進制0o或十六進制0x)。對于浮點數(shù),它可能用于顯示特殊格式(如inf、nan)。
0
在整數(shù)和浮點數(shù)格式化中,0用作填充字符,并通常與寬度一起使用,以確保數(shù)值具有指定的總寬度,并且在需要時使用零填充。
寬度:
指定字段的最小寬度。如果值比此寬度短,則使用填充字符進行填充。
分組選項:
添加千位分隔符,或連線符_。
精度:
對于浮點數(shù),.后面跟的數(shù)字指定小數(shù)點后的位數(shù)。對于字符串,它可能表示最大字段寬度。
類型:
指定要使用的格式類型,如f(浮點數(shù))、s(字符串)、d(整數(shù))等。

# 填充和對齊方式  
print('{:0>10}'.format(123))  # 使用0填充到總寬度10,右對齊: '0000000123'  
print('{:<10}'.format(123))   # 使用空格填充到總寬度10,左對齊: '123       '  
print('{:^10}'.format(123))   # 使用空格填充到總寬度10,居中對齊: '   123    '  
  
# 正負(fù)號  
print('{:+d}'.format(123))    # 顯示正號: '+123'  
print('{:-d}'.format(-123))   # 顯示負(fù)號(默認(rèn)): '-123'  
  
# # 前綴  
print('{:#010x}'.format(255)) # 十六進制,顯示0x前綴并用0填充: '0x000000ff'  
  
# 0 填充和寬度  
print('{:010d}'.format(123))  # 使用0填充到總寬度10: '0000000123'  
  
# 精度  
print('{:.2f}'.format(123.4567))  # 浮點數(shù),保留兩位小數(shù): '123.46'  
  
# 字符串類型(這里顯式指定,但通常不需要)  
print('{:s}'.format('hello'))     # 字符串: 'hello'  
print('{:d}'.format(123))         # 整數(shù): '123'  
  
# 分組選項(自定義實現(xiàn))  
number = 123456789  
formatted = '{:,}'.format(number)  # 使用逗號作為千位分隔符: '123,456,789'  
# 注意:這不是`str.format()`的內(nèi)置選項,而是利用了內(nèi)置的逗號分隔符格式化

知識檢查

  1. [#][0]用于二、八、十六進制中,前者是補前綴,后者是是在前綴后數(shù)值前補0。
  2. [精度]用于字符串時,如果實際長度比設(shè)置寬度大,有截斷字符串的作用。
print("{:.2s}".format("aaaaa")  # aa
  1. [分組選項]只適合數(shù)值,可選擇逗號,和下劃線 _
 "{:10,.2f}".format(122222.3456)   # 122,222.35
  1. [類型] d和s這兩種類型經(jīng)常可以省略

進一步練習(xí)

  1. 格式化數(shù)字
    精度格式化:
    保留指定位數(shù)的小數(shù):"{:.2f}".format(3.1415926) #輸出 3.14
    整數(shù)千位分隔符: "{:,}".format(1234567) #輸出 1,234,567
    進制轉(zhuǎn)換:
    二進制:"{:b}".format(10) #輸出 1010
    八進制:"{:o}".format(10) #輸出 12
    十六進制(小寫):"{:x}".format(255) #輸出 ff
    十六進制(大寫):"{:X}".format(255) #輸出 FF
  2. 格式化字符串
    對齊和填充:
    左對齊:"{:<10}".format("foo") #輸出 foo
    居中對齊:"{:^10}".format("bar") #輸出 bar
    右對齊:"{:>10}".format("baz") #輸出 baz
    自定義填充字符(如使用*填充):"{:*>10}".format("bar") #輸出 *****bar***
    字符串截?。?br> 截取前三個字符:"{:.3}".format("helloworld") #輸出 hel
  3. 格式化日期和時間
    使用 datetime 模塊:
    日期格式化:"{:%Y-%m-%d}".format(datetime.date(2023, 3, 15)) #輸出 2023-03-15
    時間格式化:"{:%H:%M:%S}".format(datetime.time(12, 34, 56)) #輸出 12:34:56
    日期時間格式化:"{:%Y-%m-%d %H:%M:%S}".format(datetime.datetime(2023, 3, 15, 12, 34, 56)) #輸出 2023-03-15 12:34:56
  4. 格式化對象和屬性
    訪問對象的屬性:
    假設(shè)有一個 Person 類,可以使用{0.name} 或 {name}訪問其 name 屬性。
  5. 格式化字典
    使用 ** 解包字典作為關(guān)鍵字參數(shù):
    "{name} is {age} years old".format(**{"name": "Alice", "age": 30}) #輸出 Alice is 30 years old
  6. 嵌套和轉(zhuǎn)義
    嵌套 .format():
    "{{0}} {}".format("foo", "bar") #輸出 {0} bar
    轉(zhuǎn)義大括號:
    在字符串中表示大括號 { 或 },使用 {{ 或 }} 來轉(zhuǎn)義。
  7. 格式化列表和元組
    雖然 .format() 不直接支持列表和元組的格式化,但可以通過循環(huán)、列表推導(dǎo)式或 *args 來實現(xiàn)。

知識拓展

Finally, the ‘type’ determines how the data should be presented.
The available integer presentation types are:
'b' - Binary. Outputs the number in base 2.
'c' - Character. Converts the integer to the corresponding
Unicode character before printing.
'd' - Decimal Integer. Outputs the number in base 10.
'o' - Octal format. Outputs the number in base 8.
'x' - Hex format. Outputs the number in base 16, using
lower-case letters for the digits above 9.
'X' - Hex format. Outputs the number in base 16, using
upper-case letters for the digits above 9.
'n' - Number. This is the same as 'd', except that it uses the
current locale setting to insert the appropriate
number separator characters.
'' (None) - the same as 'd'


The available floating point presentation types are:
'e' - Exponent notation. Prints the number in scientific
notation using the letter 'e' to indicate the exponent.
'E' - Exponent notation. Same as 'e' except it converts the
number to uppercase.
'f' - Fixed point. Displays the number as a fixed-point
number.
'F' - Fixed point. Same as 'f' except it converts the number
to uppercase.
'g' - General format. This prints the number as a fixed-point
number, unless the number is too large, in which case
it switches to 'e' exponent notation.
'G' - General format. Same as 'g' except switches to 'E'
if the number gets to large.
'n' - Number. This is the same as 'g', except that it uses the
current locale setting to insert the appropriate
number separator characters.
'%' - Percentage. Multiplies the number by 100 and displays
in fixed ('f') format, followed by a percent sign.
'' (None) - similar to 'g', except that it prints at least one
digit after the decimal point.
Objects are able to define their own format specifiers to replace the standard ones. An example is the ‘datetime’ class, whose format specifiers might look something like the arguments to the strftime() function:
"Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())
For all built-in types, an empty format specification will produce the equivalent of str(value). It is recommended that objects defining their own format specifiers follow this convention as well.


  • f-string 適用于--- python3.6+

f-string(格式化字符串字面值)是Python 3.6及以上版本中引入的一種簡潔的字符串格式化方法。你可以在字符串前加上f或F,并在字符串內(nèi)部使用大括號{}來包含表達式。這些表達式將在運行時被求值,并轉(zhuǎn)換為字符串。

name = "kejiangmin"  
age = 47
print(f"My name is {name} and I am {age} years old.")
number = 123456789  
width = 10  
precision = 2  
  
# 填充和對齊方式(f-string中通常不直接支持,但可以結(jié)合表達式)  
formatted = f'{"{number:0>{width}}"}'  # 使用0填充到總寬度10: '000000123456789'  
  
# 正負(fù)號(f-string直接支持)  
formatted = f'{+number}'  # 顯示正號(但通常對正數(shù)來說是多余的)  
  
# 精度(f-string直接支持)  
formatted = f'{number:.{precision}f}'  # 浮點數(shù),保留兩位小數(shù)(假設(shè)number是浮點數(shù)): '12
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容