120 likes | 219 Views
Python’s input and output. Chenghao Wang. Fancier Output Formatting – Output method. Print() Str () Repr (). Example. Diffe rence between str ( ) and repr () The str () function is meant to return representations of values which are fairly human-readable.
E N D
Python’s input and output Chenghao Wang
Fancier Output Formatting – Output method • Print() • Str() • Repr() Example Difference between str( ) and repr() The str() function is meant to return representations of values which are fairly human-readable. The repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). S=“Hello World” Print(s) OR Print(“Hello World”) - Hello World S=“Hello World” Str(s) - ‘Hello World’ S=“Hello World” Repr(s) - “‘Hello World’”
Fancier Output Formatting – Formatting Method • str.rjust() • str.ljust() • str.center() The str.rjust() method can right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods str.ljust() and str.center().
Fancier Output Formatting – Formatting Method • str.zfill() • str.format() Example '12'.zfill(5) -> '00012' '-3.14'.zfill(7) -> '-003.14' '3.14159265359'.zfill(5) ->'3.14159265359' Example print('We are the {} who say "{}!"'.format('knights', 'Ni')) -> We are the knights who say "Ni!" Example 2 print('This {food} is {adjective}.'.format( ... food='spam', adjective='absolutely horrible')) ->This spam is absolutely horrible. Example 3 import math print('The value of PI is approximately {0:.3f}.'.format(math.pi)) ->The value of PI is approximately 3.142. This method returns the numeric string left filled with zerosin a string of length width. This method can replace the brackets and characters with the objects passed into. An optional ':' and format specifier can follow the field name.
Fancier Output Formatting – Old Formatting Method • The % operator Example import math print('The value of PI is approximately %5.3f.' % math.pi) ->The value of PI is approximately 3.142. The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation.
Reading Files • open(filename, mode) Example f = open('workfile', 'w') f = open('filename', ‘r') Mode ’r’ -> open the file only for reading Mode ’w’ -> only writing (erase file with the same time) Mode ’a’ -> opens the file for appending Mode ’r+’ -> open the file for reading and writing Mode ‘b’ -> opens the file in binary mode
Reading Files • f.read(size) Example f.read() ->'This is the entire file.\n‘ f.read() ->' This method reads some quantity of data and returns it as a string or bytes object. When size is negative or omitted, then return the entire content; When the end of the file has been reached, then return empty string ‘’
Reading Files • f.readline() Example f.readline() ->'This is the first line of the file.\n' f.readline() ->'Second line of the file\n' f.readline() ->'' This method reads a single line from the file;
Writing Files • f.write(string) • f.tell() Example f.write('This is a test\n') ->15 Example value = ('the answer', 42) s = str(value) f.write(s) ->18 This method writes the contents of string to the file, returning the number of characters written. To write something other than a string, it needs to be converted to a string first. This method returns an integer giving the file object’s current position
Writing Files • f.seek(offset, from_what) • f.close() Example f = open('workfile', 'rb+') f.write(b'0123456789abcdef') ->16 f.seek(-3, 2) # Go to the 3rd byte before the end ->13 f.read(1) ->b'd' The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point, omitted means from the beginning of the file. After the writing is done, use this to close.
Saving structured data with json - Overview • json Python allows users to use the popular data interchange format called JSON (JavaScript Object Notation) to take Python data hierarchies, and convert them to string representations json.dumps([1, 'simple', 'list']) ->'[1, "simple", "list"]' If you have an object x, you can view its JSON string representation with a simple line of code: Another variant of the dumps() function, called dump(), simply serializes the object to a text file. So if f is a text file object opened for writing, we can do this: To decode the object again, if f is a text file object which has been opened for reading: x = json.load(f)) json.dump(x, f)
Thanks Works Citation The Python Tutorial https://docs.python.org/3/tutorial/inputoutput.html# Json’s Overview and python-related operations for json http://www.cnblogs.com/coser/archive/2011/12/14/2287739.html 5/21/2014