python基础(19)之 输入输出
?
目錄
?用戶輸入
一、格式化輸入輸出
二、格式化字符串字面值?
三、字符串 format() 方法
四、手動(dòng)格式化字符串
五、舊式字符串格式化方法
用戶輸入
?實(shí)在太簡(jiǎn)單了,就是使用一個(gè)input(),將輸入后的值傳遞給另一個(gè)變量,相當(dāng)于動(dòng)態(tài)賦值、
例如:
返回:
一、格式化輸入輸出
1.在字符串開頭的引號(hào)/三引號(hào)前添加 f 或 F 。在這種字符串中,可以在 { 和 } 字符之間輸入引用的變量 year = 2022 event = 'Referendum' a=f'Results of the {year} {event}' print(a)?返回:
?2.str.format() 該方法也用 { 和 } 標(biāo)記替換變量的位置a 這種方法支持詳細(xì)的格式化指令
yes_votes = 42_572_654 no_votes = 43_132_495 percentage = yes_votes / (yes_votes + no_votes) a='{:-5} YES votes {:1.1%}'.format(yes_votes, percentage)#調(diào)整{}內(nèi)部感受下 print(a)?返回:
?如果在這里有的懵,可以試著更改 {} 中的內(nèi)容,并輸出查看結(jié)果來(lái)進(jìn)行理解
3.想快速顯示變量進(jìn)行調(diào)試,可以用 repr() 或 str() 函數(shù)把值轉(zhuǎn)化為字符串
s = 'Hello, world.' print(str(s))#str() 函數(shù)返回供人閱讀的值 print(repr(s))#repr() 則生成適于解釋器讀取的值 print(str(1/7)) hellos = repr('hello') print(hellos)返回:
?
二、格式化字符串字面值
格式化字符串字面值 (簡(jiǎn)稱為 f-字符串)在字符串前加前綴 f 或 F,通過(guò) {expression} 表達(dá)式,把 Python 表達(dá)式的值添加到字符串內(nèi) 1.下例將 pi 舍入到小數(shù)點(diǎn)后三位 import math print(f'The value of pi is approximately {math.pi:.3f}.')返回:
?
?2.在 ':' 后傳遞整數(shù),為該字段設(shè)置最小字符寬度,常用于列對(duì)齊
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} for name, phone in table.items():print(f'{name:10} ==> {phone:10d}')三、字符串 format() 方法
先看看下面這個(gè)例子
print('We are the {} who say "{}!"'.format('knights', 'Ni'))?返回:
1.花括號(hào)及之內(nèi)的字符(稱為格式字段)被替換為傳遞給 str.format() 方法的對(duì)象。花括號(hào)中的數(shù)字表示傳遞給 str.format() 方法的對(duì)象所在的位置 print('{0} and {1}'.format('spam', 'eggs')) print('{1} and {0}'.format('spam', 'eggs'))2.使用關(guān)鍵字參數(shù)名引用值
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))3.位置參數(shù)和關(guān)鍵字參數(shù)可以任意組合
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))4.用方括號(hào) '[]' 訪問鍵來(lái)完成
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table))返回:
?5.也可以用 '**' 符號(hào),把 table 當(dāng)作傳遞的關(guān)鍵字參數(shù)
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))四、手動(dòng)格式化字符串
生成一組整齊的列,包含給定整數(shù)及其平方與立方
for x in range(1, 11):print('{0:2d} {1:3d} {2:4d}'.format(x, x * x, x * x * x))返回:
換種寫法如下
for x in range(1, 11):print(repr(x).rjust(2), repr(x * x).rjust(3), end=' ')print(repr(x * x * x).rjust(4))五、舊式字符串格式化方法
import math print('The value of pi is approximately %5.3f.' % math.pi) 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python基础(19)之 输入输出的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java char 空字符串_java判
- 下一篇: 辩论计算机未来不能取代书本的问题,电脑不