Python3入门指南:从2to3升级实战与字符串转型详解

5星 · 超过95%的资源 需积分: 10 6 下载量 151 浏览量 更新于2024-07-18 收藏 2.31MB PDF 举报
"《深入Python3》是一本面向初学者的优秀教程,旨在帮助读者掌握Python3语言。对于那些已经熟悉Python2或拥有原版《Dive Into Python》的程序员,本书提供了从Python2向Python3迁移的指南,特别强调了通过2to3脚本来自动化转换过程。章节1.1 'MINUS LEVEL' 指出,如果读者是Python老手,应直接进入Python3的学习,因为Python3引入了许多语法变化,如print函数升级为内置函数,变量前不再需要加``,等等。 案例研究部分详述了将一个非平凡的Python 2库移植到Python 3的经历,这可能对面临类似问题的开发者提供有价值的参考。需要注意的是,迁移过程中可能会遇到挑战,特别是字符串处理的变化。Python 3引入了Unicode字符串处理的优势,使得字符串操作更加灵活和统一。然而,这个过程需要对库的内部工作原理有深入理解,以便找出问题所在并进行修复,尤其是当库中大量依赖于旧的字符串处理方式时。 《Dive into Python3》不仅适合新手入门,也适合有一定经验的Python用户了解Python3的新特性,并学会如何在实际项目中迁移和适应新版本的语言。作者通过实例讲解和逐步指导,帮助读者逐步克服语法差异,提升编程技能。"
2019-08-18 上传
CHAPTER-1.WHAT’SNEWIN“DIVEINTO PYTHON3” ❝Isn’tthiswherewecamein?❞ —PinkFloyd,TheWall -1.1.A.K.A.“THEMINUSLEVEL” AreyoualreadyaPythonprogrammer?Didyoureadtheoriginal“DiveIntoPython”?Didyoubuyit onpaper?(Ifso,thanks!)AreyoureadytotaketheplungeintoPython3?…Ifso,readon.(Ifnoneofthat istrue,you’dbebetteroffstartingatthebeginning.) Python3comeswithascriptcalled2to3.Learnit.Loveit.Useit.PortingCodetoPython3with2to3isa referenceofallthethingsthatthe2to3toolcanfixautomatically.Sincealotofthosethingsaresyntax changes,it’sagoodstartingpointtolearnaboutalotofthesyntaxchangesinPython3.(printisnowa function,`x`doesn’twork,&c.) CaseStudy:PortingchardettoPython3documentsmy(ultimatelysuccessful)efforttoportanon-trivial libraryfromPython2toPython3.Itmayhelpyou;itmaynot.There’safairlysteeplearningcurve,since youneedtokindofunderstandthelibraryfirst,soyoucanunderstandwhyitbrokeandhowIfixedit.A lotofthebreakagecentersaroundstrings.Speakingofwhich… Strings.Whew.Wheretostart.Python2had“strings”and“Unicodestrings.”Python3has“bytes”and “strings.”Thatis,allstringsarenowUnicodestrings,andifyouwanttodealwithabagofbytes,youuse thenewbytestype.Python3willneverimplicitlyconvertbetweenstringsandbytes,soifyou’renotsure whichoneyouhaveatanygivenmoment,yourcodewillalmostcertainlybreak.ReadtheStringschapter formoredetails. Bytesvs.stringscomesupagainandagainthroughoutthebook. 1 •InFiles,you’lllearnthedifferencebetweenreadingfilesin“binary”and“text”mode.Reading(andwriting!) filesintextmoderequiresanencodingparameter.Sometextfilemethodscountcharacters,butother methodscountbytes.Ifyourcodeassumesthatonecharacter==onebyte,itwillbreakonmulti-byte characters. •InHTTPWebServices,thehttplib2modulefetchesheadersanddataoverHTTP.HTTPheadersare returnedasstrings,buttheHTTPbodyisreturnedasbytes. •InSerializingPythonObjects,you’lllearnwhythepicklemoduleinPython3definesanewdataformatthat isbackwardlyincompatiblewithPython2.(Hint:it’sbecauseofbytesandstrings.)AlsoJSON,whichdoesn’t supportthebytestypeatall.I’llshowyouhowtohackaroundthat. •InCasestudy:portingchardettoPython3,it’sjustabloodymessofbytesandstringseverywhere. Evenifyoudon’tcareaboutUnicode(ohbutyouwill),you’llwanttoreadaboutstringformattinginPython 3,whichiscompletelydifferentfromPython2. IteratorsareeverywhereinPython3,andIunderstandthemalotbetterthanIdidfiveyearsagowhenI wrote“DiveIntoPython”.Youneedtounderstandthemtoo,becauselotsoffunctionsthatusedtoreturn listsinPython2willnowreturniteratorsinPython3.Ataminimum,youshouldreadthesecondhalfof theIteratorschapterandthesecondhalfoftheAdvancedIteratorschapter. Bypopularrequest,I’veaddedanappendixonSpecialMethodNames,whichiskindoflikethePythondocs “DataModel”chapterbutwithmoresnark. WhenIwaswriting“DiveIntoPython”,alloftheavailableXMLlibrariessucked.ThenFredrikLundhwrote ElementTree,whichdoesn’tsuckatall.ThePythongodswiselyincorporatedElementTreeintothestandard library,andnowitformsthebasisformynewXMLchapter.TheoldwaysofparsingXMLarestillaround, butyoushouldavoidthem,becausetheysuck! AlsonewinPython—notinthelanguagebutinthecommunity—istheemergenceofcoderepositories likeThePythonPackageIndex(PyPI).Pythoncomeswithutilitiestopackageyourcodeinstandardformats anddistributethosepackagesonPyPI.ReadPackagingPythonLibrariesfordetails.