Python Input and OutputOutput FormattingConverting Values to Stringsstr() and repr()Justificationsrjust() exampleOther Similar Methodsstr.format()!s and !rAdditional FormattingSlide 11Reading and Writing FilesModesReadingWritingOther File MethodsSlide 17Any Questions?Python Input and OutputOutput Formatting•Two methods to format output1. Perform all string formatting yourself2. Use the str.format() methodConverting Values to Strings•Use either the str() or repr() functions•str() will return a “human-readable” representation•repr() will return representations that may be read from the interpreter•If str() is not defined for a given object, str() will return the same value as repr()str() and repr()>>> s = “hello, world\n”>>> print str(s)hello, world>>> print repr(s)‘hello, world\n’Justifications•rjust() will right-justify a string of a given width and pad it with spaces on the lefrjust() example>>> for x in range(1, 6):... print repr(x).rjust(1),... print repr(x * x).rjust(2),... print repr(x * x * x).rjust(3) 1 1 12 4 83 9 274 16 645 25 125Other Similar Methods•ljust() – for lef justification•center() – for center justification•zfill() – will pad a numeric string with 0’s on the lef•example of zfill():>>> '13'.zfill(5)'00013'>>> '-13'.zfill(5)'-0013'str.format()>>> print 'This {0} uses format {1}'.format('string', 'fields')This string uses format fields>>> print 'This {food} is {adjective}!'.format(food='spam', adjective='great')This spam is great!!s and !r•Use !s inside brackets to apply str() to the value before it is formatted•Use !r to apply repr()Additional Formatting•Use ‘:’ following the field name for additional formatting•For example, to truncate Pi to three places:>>> print 'PI is about {0:.3f}.'.format(math.pi)PI is about 3.142.•An integer afer the ‘:’ will cause the field to be a minimum number of characters wide>>> table = {'x': 120, 'y': 121, 'z': 122}>>> for char, value in table.items():... print '{0:10} ==> {1:10d}'.format(char, value)x ==> 120y ==> 121z ==> 122Reading and Writing Files•open() – returns a file object•Commonly called with two arguments1. filename2. mode>>> f = open('/temp/myfile', 'w')•close() – closes a file, freeing up system resourcesModesMode string Description‘r’ Read only (default if not specified)‘w’ Writing (will erase existing file with same name‘a’ Append‘r+’ Reading and WritingReading•filename.read(size) – read and return a specified number of bytes–filename.read() – read the entire file•filename.readline() – reads a single line from the file–keeps the ‘\n’ at the end, unless the end of file has been reached•filename.readlines() – returns a list containing each line in the fileWriting•filename.write(string) – writes the contents of the string to the file–must convert non-string values to strings first with either str() or repr()Other File Methods•filename.tell() – returns an integer representing the current position in the file–measured in bytes from the beginning of the file•filename.seek(offset, from_what) – computes a position by adding the offset to a reference point (from_what)•from_what may have 1 of 3 valuesfrom_what Description0 Beginning of file (default)1 Current position2 End of file (use a negative offset)Any
View Full Document