《Python语言程序设计》课件-第五章(中英文课件)_第1页
《Python语言程序设计》课件-第五章(中英文课件)_第2页
《Python语言程序设计》课件-第五章(中英文课件)_第3页
《Python语言程序设计》课件-第五章(中英文课件)_第4页
《Python语言程序设计》课件-第五章(中英文课件)_第5页
已阅读5页,还剩90页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Python语言程序设计【字符串的写法】PythonLanguageProgramming[Stringwriting]在Python中字符串可以用单引号('')和双引号("")标识,对于跨行的字符串可以用“三引号”(三个单引号'''或三个双引号""")标识。知识点【字符串的写法】12str1='HelloWorld!'

str2="Derisweng"【例】用单引号('')和双引号("")创建字符串12345str3="""

这是一个多行字符串的例子

使用制表符TAB(\t),也可以使用换行符\n

进行换行

"""

print(str3)【例】用三引号创建字符串这是一个多行字符串的例子使用制表符TAB( ),也可以使用换行符进行换行输出结果: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:三引号具有所见即所得的效果,其典型的应用场景就是当你需要一段HTML或者SQL语句时,如果用字符串组合或者特殊字符串转义,将会非常麻烦,而使用三引号就非常方便。知识点【字符串的写法】123456789strHTML="""

<divclass="title-box">

<h2class="title-blog">

<ahref="https://www.P">Python</a>

</h2>

<pclass="description">春江花月夜</p>

</div>

"""

print(strHTML)【例】三引号应用在HTML的定义中<divclass="title-box"><h2class="title-blog"><ahref="https://www.P">Python</a></h2><pclass="description">春江花月夜</p></div>输出结果:Threequotationmarkshavetheeffectofwhatyouseeiswhatyouget.ItstypicalapplicationscenarioisthatwhenyouneedanHTMLorSQLstatement,itwillbeverytroublesometousestringcombinationsorspecialstringstoescape.Itisveryconvenienttousethreequotationmarks.123456789strHTML="""

<divclass="title-box">

<h2class="title-blog">

<ahref="https://www.P">Python</a>

</h2>

<pclass="description">MoonlightonSpringRiver</p>

</div>

"""

print(strHTML)[Example]ThreequotationmarksareusedinthedefinitionofHTML<divclass="title-box"><h2class="title-blog"><ahref="https://www.P">Python</a></h2><pclass="description">MoonlightonSpringRiver</p></div>Outputresult:KnowledgePoints[Stringwriting]Python语言程序设计【字符串操作】PythonLanguageProgramming[Stringmanipulation]知识点【字符串操作】-1.求字符串长度12str1='HelloWorld!'

print("str1的长度:",len(str1))【例】len()函数应用str1的长度:12输出结果:KnowledgePoints[Stringmanipulation]-1.Findthelengthofthestring12str1='HelloWorld!'

print("str1length:",len(str1))[Example]Applicationoflen()functionLengthofstr1:12Outputresult:知识点【字符串操作】-2.访问字符串中的值1234str1='HelloWorld!'

str2="Python"

print("str1[0]:",str1[0])

print("str2[1:5]:",str2[1:5])【例】用方括号[]来访问子字符串str1[0]:Hstr2[1:5]:unoo输出结果:[Stringmanipulation]-2.accessingthevalueinastring1234str1='HelloWorld!'

str2="Python"

print("str1[0]:",str1[0])

print("str2[1:5]:",str2[1:5])[Example]Usingsquarebrackets[]toaccesssubstrings,thestr1[0]:Hstr2[1:5]:unooKnowledgePointsOutputresult:知识点【字符串操作】-3.字符串截取与拼接12str1='HelloWorld!'

print("更新后字符串:",str1[:6]+'Weng!')【例】字符串截取与拼接更新后字符串:HelloWeng!输出结果:[Stringmanipulation]-3.Stringtruncationandsplicing12str1='HelloWorld!'

print("Updatedstring:",str1[:6]+'Weng!')[Example]StringinterceptionandsplicingUpdatedstring:HelloWeng!KnowledgePointsOutputresult:知识点【字符串操作】-4.字符串替换1print('AACBBBCAA'.replace('BBB','AAA'))【例】字符串替换AACAAACAA输出结果:[Stringmanipulation]-4.Stringsubstitution1print('AACBBBCAA'.replace('BBB','AAA'))[Example]StringReplacementAACAAACAAKnowledgePointsOutputresult:知识点【字符串操作】-5.在字符串中查找子串并返回子串的起始位置1print("DerisWeng".find("Weng"))【例】在字符串中查找子串5输出结果:[Stringmanipulation]-5.Findingasubstringinastringandreturningthestartingpositionofthesubstring1print("DerisWeng".find("Weng"))[Example]Findingasubstringinastring5KnowledgePointsOutputresult:知识点【字符串操作】-6.大小写转换1234strU="DerisWeng".upper()

print(strU)

strL=strU.lower()

print(strL)【例】字符串大小写转换DERISWENGderisweng输出结果:[Stringmanipulation]-6.caseconversion1234strU="DerisWeng".upper()

print(strU)

strL=strU.lower()

print(strL)[Example]StringcaseconversionDERISWENGderiswengKnowledgePointsOutputresult:知识点【字符串操作】-7.去空格123print("Hello,Deris,Weng".strip())

print("Hello,Deris,Weng".lstrip())

print("Hello,Deris,Weng".rstrip())【例】去空格Hello,Deris,WengHello,Deris,WengHello,Deris,Weng输出结果:去掉两边去掉左边去掉右边[Stringmanipulation]-7.De-space123print("Hello,Deris,Weng".strip())

print("Hello,Deris,Weng".lstrip())

print("Hello,Deris,Weng".rstrip())[Example]RemovethespaceHello,Deris,WengHello,Deris,WengHello,Deris,WengRemovethesidesRemovetheleftsideRemovetherightsideKnowledgePointsOutputresult:知识点【字符串操作】-8.按标志分割字符串12print("Hello,Deris,Weng".split(","))

print("Hello,Deris,Weng".split("e"))【例】字符串用逗号分割['Hello','Deris','Weng']['H','llo,D','ris,W','ng']输出结果:按,按字符e[Stringmanipulation]-8.SplitstringbyflagKnowledgePoints12print("Hello,Deris,Weng".split(","))

print("Hello,Deris,Weng".split("e"))['Hello','Deris','Weng']['H','llo,D','ris,W','ng']accordingto“,”accordingtostring“e”[Example]SeparatestringswithcommasOutputresult:Python语言程序设计【字符串运算符+字符串格式化%】PythonLanguageProgramming[Stringoperators+stringformatting%]运

符描

述+字符串连接*字符串倍增[]通过索引获取字符串中的字符[:]截取字符串中的一部分in如果字符串中包含给定的字符,返回Truenotin如果字符串中不包含给定的字符,返回Truer/R原始字符串:所有的字符串都直接按照字面的意思来使用,没有转义特殊或不能打印的字符。原始字符串除在字符串的第一个引号前加上字母“r”(大小写均可)以外,与普通字符串有着几乎完全相同的语法%格式字符串知识点【字符串支持的常用运算符】operatorDescription+stringconcatenation*Stringmultiplication[]Getthecharactersinthestringbyindexingthe[:]InterceptsaportionofastringinReturnsTrueifthestringcontainsthegivencharacternotinReturnsTrueifthestringdoesnotcontainthegivencharacterr/ROriginalstring:Allstringsareusedliterallywithoutescapingspecialorunprintablecharacters.Theoriginalstringhasalmostthesamesyntaxastheordinarystring,exceptthattheletter"r"isaddedbeforethefirstquotationmarkofthestring(caseisacceptable)%formatstringKnowledgePoints[CommonOperatorsSupportedbyString]示例12345678910111213141516a="Deris"

b="Weng"

print("a+b输出结果:",a+b)

print("a*2输出结果:",a*2)

print("a[1]输出结果:",a[1])

print("a[1:4]输出结果:",a[1:4])

if("D"ina):

print("D在字符串a中")

else:

print("D不在字符串a中")

if("W"notina):

print("W不在字符串a中")

else:

print(“W在字符串a中")

print(r'\n')

print(R'\n')【例】字符串常用运算a+b输出结果:DerisWenga*2输出结果:DerisDerisa[1]输出结果:ea[1:4]输出结果:eriD在字符串a中W不在字符串a中\n\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:知识点【字符串格式化】-%1print("我叫%s,今年%d岁。"%('DerisWeng',18))【例】字符串格式符%s应用我叫DerisWeng,今年18岁。输出结果:Python支持格式化字符串的输出。最基本的用法是将一个值插入一个有字符串格式符

%的字符串中。[StringFormatting]-%1print("Mynameis%s,andI'm%dyearsoldthisyear."%('DerisWeng',18))[Example]Applicationofstringformatter%sMynameisDerisWeng.I'm18yearsold.Pythonsupportsformattedstringoutput.Themostbasicuseistoinsertavalueintoastringwiththestringformattingcharacter%.KnowledgePointsOutputresult:知识点【字符串格式化】-%符

号描

述%c格式化字符及其ASCII码%s格式化字符串%d格式化整数%u格式化无符号整型数%o格式化无符号八进制数%x格式化无符号十六进制数%X格式化无符号十六进制数(大写)符

号描

述%f格式化浮点数字,可指定小数点后的精度%e用科学记数法格式化浮点数%E作用同%e,用科学记数法格式化浮点数%g%f和%e的简写%G%f和%E的简写%p用十六进制数格式化变量的地址[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("该商品的售价为:%.2f"%price)【例】字符串格式符%f应用该商品的售价为:108.85输出结果:字符串格式化符号%f可指定小数点后的精度。【字符串格式化】-%Example12price=108.8528

print("Thesellingpriceofthisproductis:%.2f"%price)[Example]Applicationofstringformatter%fThesellingpriceofthisitemis:108.85Thestringformattingsymbol%fspecifiestheprecisionafterthedecimalpoint.[StringFormatting]-%Outputresult:Python语言程序设计【字符串格式化(format函数)】PythonLanguageProgrammingStringFormat(formatfunction)知识点【字符串格式化】-format函数format()方法中模板字符串的槽除了包括参数序号,还可以包括格式控制信息。此时,槽的内部样式如下:{<参数序号>:<格式控制标记>}其中,格式控制标记用来控制参数显示时的格式。格式控制标记包括:<填充><对齐><宽度>,<.精度><类型>6个字段,这些字段都是可选的,可以组合使用,这里按照使用方式逐一介绍。KnowledgePointsFormatString-formatfunctionTheslotofthetemplatestringintheformat()methodcanincludenotonlytheparameterserialnumber,butalsotheformatcontrolinformation.Atthistime,theinternalstyleoftheslotisasfollows:{<ParameterSN>:<FormatControlMark>}Theformatcontroltagsareusedtocontroltheformatoftheparameterdisplay.Formatcontroltagsinclude:<fill><alignment><width>,<.Precision><Type>6fields,thesefieldsareoptional,canbeusedincombination,hereinaccordancewiththeuseofthewaytointroduceonebyone.知识点【字符串格式化】-format函数123456#占位符{},默认顺序

print('{}{}'.format('one','two'))

print('我的姓名为{},年龄{}岁,爱好{}'.format('DerisWeng','18','dancing'))

#占位符{},指定顺序

print('{1}{0}'.format('one','two'))

print('我的姓名为{0},年龄{1}岁,爱好{2}'.format('DerisWeng','18','dancing'))【例】字符串格式符format函数应用onetwo我的姓名为DerisWeng,年龄18岁,爱好dancingtwoone我的姓名为DerisWeng,年龄18岁,爱好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函数123456789s='DerisWeng'

#默认左对齐,占30个字符

print('{:30}'.format(s))

#默认左对齐,占30个字符,此处逗号表示两个字符串按顺序显示

print('{:30}'.format(s),'abc')

#右对齐,占30个字符

print('{:>30}'.format(s))

#填充字符为-,^表示以居中方式显示,所有字符占30个位置

print('{:-^30}'.format(s))【例】字符串格式符format函数应用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函数1234567891011s='DerisWeng'

#填充字符为-,>表示以靠右方式显示,所有字符占20个位置

print('{:->20}'.format(s))

#填充字符为+,<表示以靠左方式显示,所有字符占20个位置

print('{:+<20}'.format(s))

#填充字符为q,<表示以靠左方式显示,所有字符占20个位置

print('{:q<20}'.format(s))

#填充字符为1,<表示以靠左方式显示,所有字符占20个位置

print('{:1<20}'.format(s))

#填充字符为*,>表示以靠右方式显示,所有字符占20个位置

print('{:*>20}'.format(s))【例】字符串格式符format函数应用-----------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函数12345678910#保留小数点后两位

print('{:.2f}'.format(12345678))

#千分位分隔

print('{:,}'.format(12345678))

#0表示format中的索引号index

print('{0:b},{0:c},{0:d},{0:o},{0:x}'.format(42))

#0对应42,1对应50

print('{0:b},{1:c},{0:d},{1:o},{0:x}'.format(42,50))

#默认index为0

print('{:b}'.format(42))【例】字符串格式符format函数应用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的最大输出长度为2

print('{:.2}'.format(s))

#中文

print("{:好<20}".format(s))【例】字符串格式符format函数应用DeDerisWeng好好好好好好好好好好好示例【字符串格式化】-format函数12345s='DerisWeng'

#Themaximumoutputlengthofstringsis2

print('{:.2}'.format(s))

#Chinese

print("{:good<20}".format(s))[Example]ApplicationofstringformatterformatfunctionDeDerisWeng,good,good,good,goodExampleFormatString-formatfunction12#:冒号+空白填充+右对齐+固定宽度18+浮点精度.2+浮点数声明f

print('{:>18,.2f}'.format(70305084.0))【例】要求对70305084.0进行如下格式化:右对齐(空白填充)+固定宽度18+浮点精度.2+千分位分隔

70,305,084.00输出结果::>18,.2f千分位、浮点数、填充字符、对齐的组合使用示例【字符串格式化】-format函数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))【例】复杂数据格式化——列表数据2342输出结果:示例【字符串格式化】-format函数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()))【例】复杂数据格式化——字典数据Student:Deris输出结果:示例【字符串格式化】-format函数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)等价于format(first='Deris',last='Weng',last2='Good')【例】通过字典设置参数DerisWengGood输出结果:示例【字符串格式化】-format函数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("网站名:{0[0]},地址{0[1]}".format(my_list))【例】通过列表索引设置参数网站名:Python,地址www.P输出结果:示例【字符串格式化】-format函数print("网站名:{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("{}对应的位置是{{0}}".format("Deris"))【例】使用花括号{}

来转义花括号Deris对应的位置是{0}输出结果:示例【字符串格式化】-format函数1print(thecorrespondingpositionof"{}"is{{0}}".format("Deris"))[Example]Usethecurlybraces{}toescapethecurlybracesDeriscorrespondsto{0}ExampleFormatString-formatfunctionOutputresult:123print('{:.{}}'.format('DerisWeng',7))

#等价于

print('{:.7}'.format('DerisWeng'))【例】控制长度的两种等效做法DerisWeDerisWe输出结果:示例【字符串格式化】-format函数123print('{:.{}}'.format('DerisWeng',7))

#Equivalent

print('{:.7}'.format('DerisWeng'))[Example]TwoequivalentmethodsforcontrollinglengthDerisWeDerisWeExampleFormatString-formatfunctionOutputresult:Python语言程序设计65《利用文本文件读写存储游戏过程日志》PythonLanguageProgramming66Readingandwritingstoredgameprocedurelogsusingtextfiles知识要点67利用文本文件读写存储游戏过程日志知识点6文本文件读写重要方法有:open、close、read、write、readline、readlines【例】将字符串写入到文件test.txt中#打开一个文件

f=open(“test.txt","w")

f.write("Python是一个非常好的语言。\n是的,的确非常好!!\n")

#关闭打开的文件f.close()第一个参数为要打开的文件名。第二个参数描述文件如何使用的字符。

‘r’以只读方式打开文件,‘w’打开一个文件,只用于写(如果存在同名文件则将被删除),'a'用于追加文件内容;所写的任何数据都会被自动增加到末尾.'r+'同时用于读写。'r'将是默认值。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.知识要点69考一考提问环节、答题有加分、要记笔记哦!问题1:open(filename,‘w’),这里的w是什么意思?W代表写的方式w“只写”方式每次写都是以覆盖的方式,文件之前的内容将会被覆盖;a“添加”方式则是在文件原有内容的基础上添加,并不会覆盖原有内容,所写的任何数据都会被自动增加到文件的末尾。问题2:open(filename,‘a’)中a与w的区别?KnowledgePoints70TakeatestQuestionandanswersessions,bonuspointsforansweringquestions,andtakingnotes!Question1:open(filename,'w'),whatdoeswmeanhere?WstandsforthewayofwritingW"Writeonly"modeEverywriteisoverwritten,andthecontentsbeforethefilewillbeoverwritten;A"Add"meanstoaddonthebasisoftheoriginalcontentofthefilewithoutoverwritingtheoriginalcontent,Anydatawrittenisautomaticallyaddedtotheendofthefile.Question2:Whatisthedifferencebetweenaandwinopen(filename,'a')?知识要点71利用文本文件读写存储游戏过程日志知识点61.f.read()【例】f.read()的使用#打开一个文件

f=open(“test.txt",“r")

str=f.read()print(str)#关闭打开的文件f.close()输出结果:为了读取一个文件的内容,调用f.read(size),这将读取一定数目的数据,然后作为字符串或字节对象返回。Python是一个非常好的语言。是的,的确非常好!!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知识要点73利用文本文件读写存储游戏过程日志知识点61.f.read()【例】f.read(size)的使用#打开一个文件

f=open(“test.txt",“r")

str=f.read(2)print(str)#关闭打开的文件f.close()输出结果:为了读取一个文件的内容,调用f.read(size),这将读取一定数目的数据,然后作为字符串或字节对象返回。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:知识要点75利用文本文件读写存储游戏过程日志知识点62.f.readline()【例】f.readline()读出一行#打开一个文件

f=open(“test.txt",“r")

str=f.readline()print(str)#关闭打开的文件f.close()输出结果:会从文件中读取单独的一行,换行符为’\n’。它每次读出一行内容,占用的内存小,比较适合大文件。它返回的也是字符串对象。Python是一个非常好的语言。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:知识要点77利用文本文件读写存储游戏过程日志知识点62.f.readline()【例】f.readline()读出多行输出结果:会从文件中读取单独的一行,换行符为’\n’。它每次读出一行内容,占用的内存小,比较适合大文件。它返回的也是字符串对象。Python是一个非常好的语言。是的,的确非常好!!#打开一个文件

f=open("test.txt","r")

str=f.readline()

whilestr:

print(str,end='')

str=f.readline()

#关闭打开的文件

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.知识要点79利用文本文件读写存储游戏过程日志知识点63.f.readlines()【例】f.readlines()读行输出结果:f.readlines()将返回该文件包含的所有行。它读取整个文件的所有行,并将其保存在一个列表变量中,每行作为一个元素。读取内存较大。['Python是一个非常好的语言。\n','是的,的确非常好!!\n']#打开一个文件

f=open("test.txt","r")

str=f.readlines()

print(str)

#关闭打开的文件

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:知识要点81利用文本文件读写存储游戏过程日志知识点63.f.readlines()【例】利用f.readlines()遍历读行输出结果:f.readlines()将返回该文件包含的所有行。它读取整个文件的所有行,并将其保存在一个列表变量中,每行作为一个元素。读取内存较大。Python是一个非常好的语言。是的,的确非常好!!#打开一个文件

f=open("test.txt","r")

str=f.readlines()

foriinstr:print(i,end='')

#关闭打开的文件

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. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论