版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
Python語(yǔ)言程序設(shè)計(jì)【字符串的寫法】PythonLanguageProgramming[Stringwriting]在Python中字符串可以用單引號(hào)('')和雙引號(hào)("")標(biāo)識(shí),對(duì)于跨行的字符串可以用“三引號(hào)”(三個(gè)單引號(hào)'''或三個(gè)雙引號(hào)""")標(biāo)識(shí)。知識(shí)點(diǎn)【字符串的寫法】12str1='HelloWorld!'
str2="Derisweng"【例】用單引號(hào)('')和雙引號(hào)("")創(chuàng)建字符串12345str3="""
這是一個(gè)多行字符串的例子
使用制表符TAB(\t),也可以使用換行符\n
進(jìn)行換行
"""
print(str3)【例】用三引號(hào)創(chuàng)建字符串這是一個(gè)多行字符串的例子使用制表符TAB( ),也可以使用換行符進(jìn)行換行輸出結(jié)果:InPython,stringscanbeidentifiedwithsinglequotationmarks('')anddoublequotationmarks(""),andcrosslinestringscanbeidentifiedwith"threequotationmarks"(threesinglequotationmarks''orthreedoublequotationmarks"").KnowledgePoints[Stringwriting]12str1='HelloWorld!'
str2="Derisweng"[Example]Creatingstringswithsinglequotes('')anddoublequotes("")12345str3="""
Thisisanexampleofamulti-linestring
UsetabTAB(t),orusenewlinenfornewline
"""
print(str3)[Example]CreatingastringwithtriplequotesThisisanexampleofamulti-linestringthatUseTabTAB( ),youcanalsouselinebreaks
PerformlinefeedsOutputresult:三引號(hào)具有所見(jiàn)即所得的效果,其典型的應(yīng)用場(chǎng)景就是當(dāng)你需要一段HTML或者SQL語(yǔ)句時(shí),如果用字符串組合或者特殊字符串轉(zhuǎn)義,將會(huì)非常麻煩,而使用三引號(hào)就非常方便。知識(shí)點(diǎn)【字符串的寫法】123456789strHTML="""
<divclass="title-box">
<h2class="title-blog">
<a]accordingto“,”accordingtostring“e”[Example]SeparatestringswithcommasOutputresult:Python語(yǔ)言程序設(shè)計(jì)【字符串運(yùn)算符+字符串格式化%】PythonLanguageProgramming[Stringoperators+stringformatting%]運(yùn)
算
符描
述+字符串連接*字符串倍增[]通過(guò)索引獲取字符串中的字符[:]截取字符串中的一部分in如果字符串中包含給定的字符,返回Truenotin如果字符串中不包含給定的字符,返回Truer/R原始字符串:所有的字符串都直接按照字面的意思來(lái)使用,沒(méi)有轉(zhuǎn)義特殊或不能打印的字符。原始字符串除在字符串的第一個(gè)引號(hào)前加上字母“r”(大小寫均可)以外,與普通字符串有著幾乎完全相同的語(yǔ)法%格式字符串知識(shí)點(diǎn)【字符串支持的常用運(yùn)算符】operatorDescription+stringconcatenation*Stringmultiplication[]Getthecharactersinthestringbyindexingthe[:]InterceptsaportionofastringinReturnsTrueifthestringcontainsthegivencharacternotinReturnsTrueifthestringdoesnotcontainthegivencharacterr/ROriginalstring:Allstringsareusedliterallywithoutescapingspecialorunprintablecharacters.Theoriginalstringhasalmostthesamesyntaxastheordinarystring,exceptthattheletter"r"isaddedbeforethefirstquotationmarkofthestring(caseisacceptable)%formatstringKnowledgePoints[CommonOperatorsSupportedbyString]示例12345678910111213141516a="Deris"
b="Weng"
print("a+b輸出結(jié)果:",a+b)
print("a*2輸出結(jié)果:",a*2)
print("a[1]輸出結(jié)果:",a[1])
print("a[1:4]輸出結(jié)果:",a[1:4])
if("D"ina):
print("D在字符串a(chǎn)中")
else:
print("D不在字符串a(chǎn)中")
if("W"notina):
print("W不在字符串a(chǎn)中")
else:
print(“W在字符串a(chǎn)中")
print(r'\n')
print(R'\n')【例】字符串常用運(yùn)算a+b輸出結(jié)果:DerisWenga*2輸出結(jié)果:DerisDerisa[1]輸出結(jié)果:ea[1:4]輸出結(jié)果:eriD在字符串a(chǎn)中W不在字符串a(chǎn)中\(zhòng)n\n輸出結(jié)果:【字符串支持的常用運(yùn)算符】Example12345678910111213141516a="Deris"
b="Weng"
print("a+boutputresult:",a+b)
print("a*2Outputresult:",a*2)
print("a[1]Outputresult:",a[1])
print("a[1:4]outputresult:",a[1:4])
if("D"ina):
print("Dinstringa")
else:
print("Disnotinthestringa")
if("W"notina):
print("Wisnotinthestringa")
else:
print("Winstringa")
print(r'\n')
print(R'\n')[Example]CommonoperationsonstringsA+bOutputresult:DerisWengA*2Outputresult:DerisDerisA[1]Outputresult:eA[1:4]Outputresult:eriDinstringaWisnotinthestringa\n\n[CommonOperatorsSupportedbyString]Outputresult:知識(shí)點(diǎn)【字符串格式化】-%1print("我叫%s,今年%d歲。"%('DerisWeng',18))【例】字符串格式符%s應(yīng)用我叫DerisWeng,今年18歲。輸出結(jié)果:Python支持格式化字符串的輸出。最基本的用法是將一個(gè)值插入一個(gè)有字符串格式符
%的字符串中。[StringFormatting]-%1print("Mynameis%s,andI'm%dyearsoldthisyear."%('DerisWeng',18))[Example]Applicationofstringformatter%sMynameisDerisWeng.I'm18yearsold.Pythonsupportsformattedstringoutput.Themostbasicuseistoinsertavalueintoastringwiththestringformattingcharacter%.KnowledgePointsOutputresult:知識(shí)點(diǎn)【字符串格式化】-%符
號(hào)描
述%c格式化字符及其ASCII碼%s格式化字符串%d格式化整數(shù)%u格式化無(wú)符號(hào)整型數(shù)%o格式化無(wú)符號(hào)八進(jìn)制數(shù)%x格式化無(wú)符號(hào)十六進(jìn)制數(shù)%X格式化無(wú)符號(hào)十六進(jìn)制數(shù)(大寫)符
號(hào)描
述%f格式化浮點(diǎn)數(shù)字,可指定小數(shù)點(diǎn)后的精度%e用科學(xué)記數(shù)法格式化浮點(diǎn)數(shù)%E作用同%e,用科學(xué)記數(shù)法格式化浮點(diǎn)數(shù)%g%f和%e的簡(jiǎn)寫%G%f和%E的簡(jiǎn)寫%p用十六進(jìn)制數(shù)格式化變量的地址[StringFormatting]-%SymbolDescription%cFormattingcharactersandtheirASCIIcodes%sformattingstrings%dformattingintegers%uformattinganunsignedinteger%oformattinganunsignedoctalnumber%xformattinganunsignedhexadecimalnumber%XFormattingunsignedhexadecimalnumbers(uppercase)SymbolDescription%fFormatsfloating-pointnumbers,specifyingtheprecisionafterthedecimalpoint%eformattingfloating-pointnumbersinscientificnotation%ESameas%e,usescientificnotationtoformatfloatingpointnumbers%g%Shortforfand%e%G%Shortforfand%E%pAddressesofvariablesformattedashexadecimalnumbersKnowledgePoints示例12price=108.8528
print("該商品的售價(jià)為:%.2f"%price)【例】字符串格式符%f應(yīng)用該商品的售價(jià)為:108.85輸出結(jié)果:字符串格式化符號(hào)%f可指定小數(shù)點(diǎn)后的精度。【字符串格式化】-%Example12price=108.8528
print("Thesellingpriceofthisproductis:%.2f"%price)[Example]Applicationofstringformatter%fThesellingpriceofthisitemis:108.85Thestringformattingsymbol%fspecifiestheprecisionafterthedecimalpoint.[StringFormatting]-%Outputresult:Python語(yǔ)言程序設(shè)計(jì)【字符串格式化(format函數(shù))】PythonLanguageProgrammingStringFormat(formatfunction)知識(shí)點(diǎn)【字符串格式化】-format函數(shù)format()方法中模板字符串的槽除了包括參數(shù)序號(hào),還可以包括格式控制信息。此時(shí),槽的內(nèi)部樣式如下:{<參數(shù)序號(hào)>:<格式控制標(biāo)記>}其中,格式控制標(biāo)記用來(lái)控制參數(shù)顯示時(shí)的格式。格式控制標(biāo)記包括:<填充><對(duì)齊><寬度>,<.精度><類型>6個(gè)字段,這些字段都是可選的,可以組合使用,這里按照使用方式逐一介紹。KnowledgePointsFormatString-formatfunctionTheslotofthetemplatestringintheformat()methodcanincludenotonlytheparameterserialnumber,butalsotheformatcontrolinformation.Atthistime,theinternalstyleoftheslotisasfollows:{<ParameterSN>:<FormatControlMark>}Theformatcontroltagsareusedtocontroltheformatoftheparameterdisplay.Formatcontroltagsinclude:<fill><alignment><width>,<.Precision><Type>6fields,thesefieldsareoptional,canbeusedincombination,hereinaccordancewiththeuseofthewaytointroduceonebyone.知識(shí)點(diǎn)【字符串格式化】-format函數(shù)123456#占位符{},默認(rèn)順序
print('{}{}'.format('one','two'))
print('我的姓名為{},年齡{}歲,愛(ài)好{}'.format('DerisWeng','18','dancing'))
#占位符{},指定順序
print('{1}{0}'.format('one','two'))
print('我的姓名為{0},年齡{1}歲,愛(ài)好{2}'.format('DerisWeng','18','dancing'))【例】字符串格式符format函數(shù)應(yīng)用onetwo我的姓名為DerisWeng,年齡18歲,愛(ài)好dancingtwoone我的姓名為DerisWeng,年齡18歲,愛(ài)好dancing123456#Placeholders{},defaultorder
print('{}{}'.format('one','two'))
print'Mynameis{},ageis{},hobbyis{}'.format('DerisWeng','18','dancing'))
#Placeholder{},specifyingtheorderinwhichthe
print('{1}{0}'.format('one','two'))
print'Mynameis{0},ageis{1},hobbyis{2}'.format('DerisWeng','18','dancing'))[Example]ApplicationofstringformatterformatfunctiononetwoMynameisDerisWeng.I'm18yearsold.IlikedancingtwooneMynameisDerisWeng.I'm18yearsold.IlikedancingKnowledgePointsFormatString-formatfunction示例【字符串格式化】-format函數(shù)123456789s='DerisWeng'
#默認(rèn)左對(duì)齊,占30個(gè)字符
print('{:30}'.format(s))
#默認(rèn)左對(duì)齊,占30個(gè)字符,此處逗號(hào)表示兩個(gè)字符串按順序顯示
print('{:30}'.format(s),'abc')
#右對(duì)齊,占30個(gè)字符
print('{:>30}'.format(s))
#填充字符為-,^表示以居中方式顯示,所有字符占30個(gè)位置
print('{:-^30}'.format(s))【例】字符串格式符format函數(shù)應(yīng)用DerisWengDerisWengabcDerisWeng----------DerisWeng-----------ExampleFormatString-formatfunction123456789s='DerisWeng'
#Defaultleft-justified,30characters
print('{:30}'.format(s))
#Defaultleft-justified,occupies30characters,herethecommaindicatesthatthetwostringsaredisplayedinorder
print('{:30}'.format(s),'abc')
#Right-aligned,30characters
print('{:>30}'.format(s))
#Filledwith-,^characterstoindicatecentereddisplay,withallcharactersoccupying30positions
print('{:-^30}'.format(s))[Example]ApplicationofstringformatterformatfunctionDerisWengDerisWengabcDerisWeng----------DerisWeng-----------示例【字符串格式化】-format函數(shù)1234567891011s='DerisWeng'
#填充字符為-,>表示以靠右方式顯示,所有字符占20個(gè)位置
print('{:->20}'.format(s))
#填充字符為+,<表示以靠左方式顯示,所有字符占20個(gè)位置
print('{:+<20}'.format(s))
#填充字符為q,<表示以靠左方式顯示,所有字符占20個(gè)位置
print('{:q<20}'.format(s))
#填充字符為1,<表示以靠左方式顯示,所有字符占20個(gè)位置
print('{:1<20}'.format(s))
#填充字符為*,>表示以靠右方式顯示,所有字符占20個(gè)位置
print('{:*>20}'.format(s))【例】字符串格式符format函數(shù)應(yīng)用-----------DerisWengDerisWeng+++++++++++DerisWengqqqqqqqqqqqDerisWeng11111111111***********DerisWeng1234567891011s='DerisWeng'
#Filledwith-,>characterstoindicatearight-handeddisplay,withallcharactersoccupying20positions
print('{:->20}'.format(s))
#Filledwith+,<characterstoindicatethattheyaredisplayedinaleft-handedmanner,withallcharactersoccupying20positions
print('{:+<20}'.format(s))
#Thefillingcharacterisq,<indicatesthatitisdisplayedontheleft,andallcharactersoccupy20positions
print('{:q<20}'.format(s))
#Fillcharacteris1,<meansdisplayinleft-handedmode,allcharactersoccupy20positions
print('{:1<20}'.format(s))
#Filledcharacters*,>indicatethattheyaredisplayedinaright-handedmanner,withallcharactersoccupying20positions
print('{:*>20}'.format(s))[Example]Applicationofstringformatterformatfunction-----------DerisWengDerisWeng+++++++++++DerisWengqqqqqqqqqqqDerisWeng11111111111***********DerisWengExampleFormatString-formatfunction示例【字符串格式化】-format函數(shù)12345678910#保留小數(shù)點(diǎn)后兩位
print('{:.2f}'.format(12345678))
#千分位分隔
print('{:,}'.format(12345678))
#0表示format中的索引號(hào)index
print('{0:b},{0:c},{0:d},{0:o},{0:x}'.format(42))
#0對(duì)應(yīng)42,1對(duì)應(yīng)50
print('{0:b},{1:c},{0:d},{1:o},{0:x}'.format(42,50))
#默認(rèn)index為0
print('{:b}'.format(42))【例】字符串格式符format函數(shù)應(yīng)用12345678.0012,345,678101010,*,42,52,2a101010,2,42,62,2a10101012345678910#Retaintwodecimalplaces
print('{:.2f}'.format(12345678))
#Separatedbythousandths
print('{:,}'.format(12345678))
#0indicatestheindexnumberinformat
print('{0:b},{0:c},{0:d},{0:o},{0:x}'.format(42))
#0for42,1for50#
print('{0:b},{1:c},{0:d},{1:o},{0:x}'.format(42,50))
#Thedefaultindexis0
print('{:b}'.format(42))[Example]Applicationofstringformatterformatfunction12345678.0012,345,678101010,*,42,52,2a101010,2,42,62,2a101010ExampleFormatString-formatfunction12345s='DerisWeng'
#字符串s的最大輸出長(zhǎng)度為2
print('{:.2}'.format(s))
#中文
print("{:好<20}".format(s))【例】字符串格式符format函數(shù)應(yīng)用DeDerisWeng好好好好好好好好好好好示例【字符串格式化】-format函數(shù)12345s='DerisWeng'
#Themaximumoutputlengthofstringsis2
print('{:.2}'.format(s))
#Chinese
print("{:good<20}".format(s))[Example]ApplicationofstringformatterformatfunctionDeDerisWeng,good,good,good,goodExampleFormatString-formatfunction12#:冒號(hào)+空白填充+右對(duì)齊+固定寬度18+浮點(diǎn)精度.2+浮點(diǎn)數(shù)聲明f
print('{:>18,.2f}'.format(70305084.0))【例】要求對(duì)70305084.0進(jìn)行如下格式化:右對(duì)齊(空白填充)+固定寬度18+浮點(diǎn)精度.2+千分位分隔
70,305,084.00輸出結(jié)果::>18,.2f千分位、浮點(diǎn)數(shù)、填充字符、對(duì)齊的組合使用示例【字符串格式化】-format函數(shù)12#:colon+blankfill+rightalignment+fixedwidth18+floatingpointprecision.2+floatingpointnumberdeclarationf
print('{:>18,.2f}'.format(70305084.0))[Example]Thefollowingformattingisrequiredfor70305084.0.
right-aligned(blank-filled)+fixed-width18+floating-pointprecision.2+thousandthsseparator
70,305,084.00:>18,.2fThecombineduseofthousandths,floating-pointnumbers,paddedcharacters,alignedExampleFormatString-formatfunctionOutputresult:12data=[4,8,15,16,23,42]
print('{d[4]}{d[5]}'.format(d=data))【例】復(fù)雜數(shù)據(jù)格式化——列表數(shù)據(jù)2342輸出結(jié)果:示例【字符串格式化】-format函數(shù)12data=[4,8,15,16,23,42]
print('{d[4]}{d[5]}'.format(d=data))[Example]ComplexDataFormatting-ListData2342ExampleFormatString-formatfunctionOutputresult:1234classPlant(object):
type='Student'
kinds=[{'name':'Deris'},{'name':'Christopher'}]
print('{p.type}:{p.kinds[0][name]}'.format(p=Plant()))【例】復(fù)雜數(shù)據(jù)格式化——字典數(shù)據(jù)Student:Deris輸出結(jié)果:示例【字符串格式化】-format函數(shù)1234classPlant(object):
type='Student'
kinds=[{'name':'Deris'},{'name':'Christopher'}]
print('{p.type}:{p.kinds[0][name]}'.format(p=Plant()))[Example]ComplexDataFormatting-DictionaryDataStudent:DerisExampleFormatString-formatfunctionOutputresult:1234data={'first':‘Deris','last':‘Weng','last2':‘Good'}
print('{first}{last}{last2}'.format(**data))
#format(**data)等價(jià)于format(first='Deris',last='Weng',last2='Good')【例】通過(guò)字典設(shè)置參數(shù)DerisWengGood輸出結(jié)果:示例【字符串格式化】-format函數(shù)1234data={'first':‘Deris','last':‘Weng','last2':‘Good'}
print('{first}{last}{last2}'.format(**data))
#Format(**data)isequivalenttoformat(first='Deris',last='Weng',last2='Good')[Example]SettingparametersbydictionaryDerisWengGoodExampleFormatString-formatfunctionOutputresult:12my_list=['Python','www.P']
print("網(wǎng)站名:{0[0]},地址{0[1]}".format(my_list))【例】通過(guò)列表索引設(shè)置參數(shù)網(wǎng)站名:Python,地址www.P輸出結(jié)果:示例【字符串格式化】-format函數(shù)print("網(wǎng)站名:{d[0]},地址{d[1]}".format(d=my_list))12my_list=['Python','www.P']
print("Websitename:{0[0]},address:{0[1]}".format(my_list))[Example]SettingparametersbylistindexWebsitename:Python,address:www.Python.comprint("Websitename:{d[0]},address:{d[1]}".format(d=my_list))ExampleFormatString-formatfunctionOutputresult:1print("{}對(duì)應(yīng)的位置是{{0}}".format("Deris"))【例】使用花括號(hào){}
來(lái)轉(zhuǎn)義花括號(hào)Deris對(duì)應(yīng)的位置是{0}輸出結(jié)果:示例【字符串格式化】-format函數(shù)1print(thecorrespondingpositionof"{}"is{{0}}".format("Deris"))[Example]Usethecurlybraces{}toescapethecurlybracesDeriscorrespondsto{0}ExampleFormatString-formatfunctionOutputresult:123print('{:.{}}'.format('DerisWeng',7))
#等價(jià)于
print('{:.7}'.format('DerisWeng'))【例】控制長(zhǎng)度的兩種等效做法DerisWeDerisWe輸出結(jié)果:示例【字符串格式化】-format函數(shù)123print('{:.{}}'.format('DerisWeng',7))
#Equivalent
print('{:.7}'.format('DerisWeng'))[Example]TwoequivalentmethodsforcontrollinglengthDerisWeDerisWeExampleFormatString-formatfunctionOutputresult:Python語(yǔ)言程序設(shè)計(jì)65《利用文本文件讀寫存儲(chǔ)游戲過(guò)程日志》PythonLanguageProgramming66Readingandwritingstoredgameprocedurelogsusingtextfiles知識(shí)要點(diǎn)67利用文本文件讀寫存儲(chǔ)游戲過(guò)程日志知識(shí)點(diǎn)6文本文件讀寫重要方法有:open、close、read、write、readline、readlines【例】將字符串寫入到文件test.txt中#打開(kāi)一個(gè)文件
f=open(“test.txt","w")
f.write("Python是一個(gè)非常好的語(yǔ)言。\n是的,的確非常好!!\n")
#關(guān)閉打開(kāi)的文件f.close()第一個(gè)參數(shù)為要打開(kāi)的文件名。第二個(gè)參數(shù)描述文件如何使用的字符。
‘r’以只讀方式打開(kāi)文件,‘w’打開(kāi)一個(gè)文件,只用于寫(如果存在同名文件則將被刪除),'a'用于追加文件內(nèi)容;所寫的任何數(shù)據(jù)都會(huì)被自動(dòng)增加到末尾.'r+'同時(shí)用于讀寫。'r'將是默認(rèn)值。KnowledgePoints68ReadingandwritingstoredgameprocedurelogsusingtextfilesKnowledgepoint6Importantmethodsforreadingandwritingtextfilesare.open、close、read、write、readline、readlines[Example]Writethestringtothefiletest.txt#Openafile
f=open(“test.txt","w")
f.write("Pythonisaverygoodlanguage.\nYes,verygoodindeed!!!!\n")
#Closetheopenfilef.close()Thefirstargumentisthenameofthefiletobeopened.Thesecondparameterdescribeshowthefileusesthecharacters.
'r'Openthefileasread-only,'w'opensafileforwritingonly(ifafilewiththesamenameexists,itwillbedeleted),'a'isusedtoappendfilecontent;Anydatawrittenwillbeautomaticallyaddedtotheend'r+'isalsousedforreadingandwriting.'R'willbethedefaultvalue.知識(shí)要點(diǎn)69考一考提問(wèn)環(huán)節(jié)、答題有加分、要記筆記哦!問(wèn)題1:open(filename,‘w’),這里的w是什么意思?W代表寫的方式w“只寫”方式每次寫都是以覆蓋的方式,文件之前的內(nèi)容將會(huì)被覆蓋;a“添加”方式則是在文件原有內(nèi)容的基礎(chǔ)上添加,并不會(huì)覆蓋原有內(nèi)容,所寫的任何數(shù)據(jù)都會(huì)被自動(dòng)增加到文件的末尾。問(wèn)題2:open(filename,‘a(chǎn)’)中a與w的區(qū)別?KnowledgePoints70TakeatestQuestionandanswersessions,bonuspointsforansweringquestions,andtakingnotes!Question1:open(filename,'w'),whatdoeswmeanhere?WstandsforthewayofwritingW"Writeonly"modeEverywriteisoverwritten,andthecontentsbeforethefilewillbeoverwritten;A"Add"meanstoaddonthebasisoftheoriginalcontentofthefilewithoutoverwritingtheoriginalcontent,Anydatawrittenisautomaticallyaddedtotheendofthefile.Question2:Whatisthedifferencebetweenaandwinopen(filename,'a')?知識(shí)要點(diǎn)71利用文本文件讀寫存儲(chǔ)游戲過(guò)程日志知識(shí)點(diǎn)61.f.read()【例】f.read()的使用#打開(kāi)一個(gè)文件
f=open(“test.txt",“r")
str=f.read()print(str)#關(guān)閉打開(kāi)的文件f.close()輸出結(jié)果:為了讀取一個(gè)文件的內(nèi)容,調(diào)用f.read(size),這將讀取一定數(shù)目的數(shù)據(jù),然后作為字符串或字節(jié)對(duì)象返回。Python是一個(gè)非常好的語(yǔ)言。是的,的確非常好!!KnowledgePoints721.f.read()[Example]Useoff.read()#Openafile
f=open(“test.txt",“r")
str=f.read()print(str)#Closetheopenfilef.close()Outputresult:Toreadthecontentsofafile,callf.read(size),whichwillreadacertainnumberofdata,Itisthenreturnedasastringorbyteobject.Pythonisaverygoodlanguage.Yes,verygoodindeed!!!!ReadingandwritingstoredgameprocedurelogsusingtextfilesKnowledgepoint6知識(shí)要點(diǎn)73利用文本文件讀寫存儲(chǔ)游戲過(guò)程日志知識(shí)點(diǎn)61.f.read()【例】f.read(size)的使用#打開(kāi)一個(gè)文件
f=open(“test.txt",“r")
str=f.read(2)print(str)#關(guān)閉打開(kāi)的文件f.close()輸出結(jié)果:為了讀取一個(gè)文件的內(nèi)容,調(diào)用f.read(size),這將讀取一定數(shù)目的數(shù)據(jù),然后作為字符串或字節(jié)對(duì)象返回。PyKnowledgePoints741.f.read()[Example]Useoff.read(size)#Openafile
f=open(“test.txt",“r")
str=f.read(2)print(str)#Closetheopenfilef.close()Toreadthecontentsofafile,callf.read(size),whichwillreadacertainnumberofdata,Itisthenreturnedasastringorbyteobject.PyReadingandwritingstoredgameprocedurelogsusingtextfilesKnowledgepoint6Outputresult:知識(shí)要點(diǎn)75利用文本文件讀寫存儲(chǔ)游戲過(guò)程日志知識(shí)點(diǎn)62.f.readline()【例】f.readline()讀出一行#打開(kāi)一個(gè)文件
f=open(“test.txt",“r")
str=f.readline()print(str)#關(guān)閉打開(kāi)的文件f.close()輸出結(jié)果:會(huì)從文件中讀取單獨(dú)的一行,換行符為’\n’。它每次讀出一行內(nèi)容,占用的內(nèi)存小,比較適合大文件。它返回的也是字符串對(duì)象。Python是一個(gè)非常好的語(yǔ)言。KnowledgePoints762.f.readline()[Example]f.readline()readsaline#Openafile
f=open(“test.txt",“r")
str=f.readline()print(str)#Closetheopenfilef.close()Aseparatelinewillbereadfromthefile,andthenewlinecharacteris'n'.Itreadsonelineatatime,occupiesasmallamountofmemory,andissuitableforlargefiles.Italsoreturnsastringobject.Pythonisaverygoodlanguage.ReadingandwritingstoredgameprocedurelogsusingtextfilesKnowledgepoint6Outputresult:知識(shí)要點(diǎn)77利用文本文件讀寫存儲(chǔ)游戲過(guò)程日志知識(shí)點(diǎn)62.f.readline()【例】f.readline()讀出多行輸出結(jié)果:會(huì)從文件中讀取單獨(dú)的一行,換行符為’\n’。它每次讀出一行內(nèi)容,占用的內(nèi)存小,比較適合大文件。它返回的也是字符串對(duì)象。Python是一個(gè)非常好的語(yǔ)言。是的,的確非常好!!#打開(kāi)一個(gè)文件
f=open("test.txt","r")
str=f.readline()
whilestr:
print(str,end='')
str=f.readline()
#關(guān)閉打開(kāi)的文件
f.close()KnowledgePoints782.f.readline()[Example]f.readline()readsmultiplelinesPythonisaverygoodlanguage.Yes,verygoodindeed!!!!#Openafile
f=open("test.txt","r")
str=f.readline()
whilestr:
print(str,end='')
str=f.readline()
#Closetheopenfile
f.close()ReadingandwritingstoredgameprocedurelogsusingtextfilesKnowledgepoint6Outputresult:Aseparatelinewillbereadfromthefile,andthenewlinecharacteris'n'.Itreadsonelineatatime,occupiesasmallamountofmemory,andissuitableforlargefiles.Italsoreturnsastringobject.知識(shí)要點(diǎn)79利用文本文件讀寫存儲(chǔ)游戲過(guò)程日志知識(shí)點(diǎn)63.f.readlines()【例】f.readlines()讀行輸出結(jié)果:f.readlines()將返回該文件包含的所有行。它讀取整個(gè)文件的所有行,并將其保存在一個(gè)列表變量中,每行作為一個(gè)元素。讀取內(nèi)存較大。['Python是一個(gè)非常好的語(yǔ)言。\n','是的,的確非常好!!\n']#打開(kāi)一個(gè)文件
f=open("test.txt","r")
str=f.readlines()
print(str)
#關(guān)閉打開(kāi)的文件
f.close()KnowledgePoints803.f.readlines()[Example]f.readlines()readlinef.Readlines()willreturnallthelinescontainedinthefile.Itreadsalllinesoftheentirefileandsavestheminalistvariable,witheachlineasanelement.Thereadmemoryislarge.['Pythonisaverygoodlanguage.n','Yes,verygoodindeed!!n']#Openafile
f=open("test.txt","r")
str=f.readlines()
print(str)
#Closetheopenfile
f.close()ReadingandwritingstoredgameprocedurelogsusingtextfilesKnowledgepoint6Outputresult:知識(shí)要點(diǎn)81利用文本文件讀寫存儲(chǔ)游戲過(guò)程日志知識(shí)點(diǎn)63.f.readlines()【例】利用f.readlines()遍歷讀行輸出結(jié)果:f.readlines()將返回該文件包含的所有行。它讀取整個(gè)文件的所有行,并將其保存在一個(gè)列表變量中,每行作為一個(gè)元素。讀取內(nèi)存較大。Python是一個(gè)非常好的語(yǔ)言。是的,的確非常好!!#打開(kāi)一個(gè)文件
f=open("test.txt","r")
str=f.readlines()
foriinstr:print(i,end='')
#關(guān)閉打開(kāi)的文件
f.close()KnowledgePoints823.f.readlines()[Example]Usef.readlines()totraverseandreadlinesf.Readlines()willreturnallthelinescontainedinthefile.Itreadsalllinesoftheentirefileandsavestheminalistvariable,witheachlineasanelement.Thereadmemoryislarge.Pythonisaverygoodlanguage.Yes,verygoodindeed!!!!#Openafile
f=open("test.txt","r")
str=f.readlines()
foriinstr:print(i,end='')
#Closetheopenfile
f.close()ReadingandwritingstoredgameprocedurelogsusingtextfilesKnowledgepoint
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 代理招生業(yè)務(wù)合同
- 投資監(jiān)測(cè)委托合同
- 戶外運(yùn)動(dòng)木地板購(gòu)銷協(xié)議
- 酒樓合作經(jīng)營(yíng)合同
- 信用社借款合同樣式
- 房產(chǎn)買賣合同格式模板
- 涵管生產(chǎn)廠家采購(gòu)合同
- 購(gòu)銷合同國(guó)際旅游合作發(fā)展
- 預(yù)售房屋買賣合同條款
- 全面月嫂合同范本
- 三級(jí)安全教育試題(公司級(jí)、部門級(jí)、班組級(jí))
- 2024年金融工作會(huì)議
- 2024年人教版八年級(jí)生物上冊(cè)期末考試卷(附答案)
- 開(kāi)發(fā)思路方案
- 平面的投影完整版本
- 第八單元試題-2024-2025學(xué)年統(tǒng)編版語(yǔ)文四年級(jí)上冊(cè)
- 人教版五年級(jí)上冊(cè)數(shù)學(xué)期末考試試卷含答案
- 2024年大學(xué)試題(管理類)-薪酬管理考試近5年真題集錦(頻考類試題)帶答案
- 北師大版四年級(jí)上冊(cè)書法練習(xí)指導(dǎo)-教案
- 初中道德與法治全六冊(cè)復(fù)習(xí)提綱
- 2024年中級(jí)消防員考試題庫(kù)
評(píng)論
0/150
提交評(píng)論