python’s input and output chenghao wang. fancier output formatting – output method ▪print()...

12
Python’s input and output Chenghao Wang

Upload: candace-reynolds

Post on 17-Dec-2015

219 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

 Python’s input and outputChenghao Wang

Page 2: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

Fancier Output Formatting – Output method

▪ Print()

▪ Str()

▪ Repr()

Example

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’”

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).

Page 3: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

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().

Page 4: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

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'

This method returns the numeric string left filled with zeros in a string of length width.

This method can replace the brackets and characters with the objects passed into.

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 mathprint('The value of PI is approximately {0:.3f}.'.format(math.pi))

->The value of PI is approximately 3.142.An optional ':' and format specifier can

follow the field name.

Page 5: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

Fancier Output Formatting – Old Formatting Method

▪ The % operatorExample

import mathprint('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.

Page 6: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

Reading Files

▪ open(filename, mode)Example

f = open('workfile', 'w')

f = open('filename', ‘r')

Mode ’r’ -> open the file only for readingMode ’w’ -> only writing (erase file with the same time)Mode ’a’ -> opens the file for appendingMode ’r+’ -> open the file for reading and writingMode ‘b’ -> opens the file in binary mode

Page 7: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

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 ‘’

Page 8: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

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;

Page 9: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

Writing Files

▪ f.write(string)

▪ f.tell()

Example

f.write('This is a test\n')->15

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.

Example

value = ('the answer', 42)s = str(value)f.write(s)->18

This method returns an integer giving the file object’s current position

Page 10: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

Writing Files

▪ f.seek(offset, from_what)

▪ f.close()

Example f = open('workfile', 'rb+')f.write(b'0123456789abcdef')->16f.seek(-3, 2) # Go to the 3rd byte before the end->13f.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.

Page 11: Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello

Saving structured data with json - Overview

▪ json

json.dumps([1, 'simple', 'list'])->'[1, "simple", "list"]'

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

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:

json.dump(x, f)To decode the object again, if f is a text file object which has been opened for reading:

x = json.load(f))