Lakshit Dhanda. Output Formatting Python has ways to convert any value to a string. 2 Methods repr() – meant to generate representations of values read.

Slides:



Advertisements
Similar presentations
Python Basics: Statements Expressions Loops Strings Functions.
Advertisements

CPS120: Introduction to Computer Science INPUT/OUTPUT.
Μαθαίνοντας Python [Κ4] ‘Guess the Number’
Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello.
Input from STDIN STDIN, standard input, comes from the keyboard. STDIN can also be used with file re-direction from the command line. For instance, if.
CS1061 C Programming Lecture 16: Formatted I/0 A. O’Riordan, 2004.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Printing. printf: formatted printing So far we have just been copying stuff from standard-in, files, pipes, etc to the screen or another file. Say I have.
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(,,,..., );
Fundamentals of Python: From First Programs Through Data Structures
Ping Zhang 10/08/2010.  You can get data from the user (input) and display information to the user (output).  However, you must include the library.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Input, Output, and Processing
Formatting, Casts, Special Operators and Round Off Errors 09/18/13.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Python: Input and Output Yuen Kwan Lo. Output Format str( ) and repr( ) same representation but String and Floating point number a=0.24 str(a)‘0.24’ repr.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Python Crash Course File I/O Bachelors V1.0 dd Hour 2.
Artificial Intelligence Lecture No. 26 Dr. Asad Ali Safi ​ Assistant Professor, Department of Computer Science, COMSATS Institute of Information Technology.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
Files Tutor: You will need ….
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Formatting Output. Line Endings By now, you’ve noticed that the print( ) function will automatically print out a new line after passing all of the arguments.
Python Let’s get started!.
ASC, National Centre for Physics Programming Python – Lecture#2 Mr. Adeel-ur-Rehman.
Input and Output in python Josh DiCristo. How to output numbers str()  You can put any variable holding a number inside the parentheses and it will display.
5 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
1 Essential Computing for Bioinformatics Bienvenido Vélez UPR Mayaguez Lecture 3 High-level Programming with Python Part III: Files and Directories Reference:
Kanel Nang.  Two methods of formatting output ◦ Standard string slicing and concatenation operations ◦ str.format() method ie. >>> a = “The sum of 1.
Python focus – files The open keyword returns a file object Opening a file myFile = open('C:\file.txt', arg) Optional argument The second argument controls.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Formatted I/O ä ä Standard Output ä ä printf() family of functions ä ä Standard Input ä ä scanf() family of functions.
CSI 32 Lecture 20 Chapter 8 Input, Output, and Files 8.1 Standard Input and Output (review) 8.2 Formatted Strings 8.3 Working with Files 8.5 Case Studies.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
Introduction to Programming
Python Variable Types.
Python Let’s get started!.
Line Continuation, Output Formatting, and Decision Structures
Formatting Output.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
CPS120: Introduction to Computer Science
TMF1414 Introduction to Programming
File Access (7.5) CSE 2031 Fall July 2018.
Python’s input and output
Dictionaries, File operations
Strings A string is a sequence of characters treated as a group
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Line Continuation, Output Formatting, and Decision Structures
Lecture 13 Input/Output Files.
And now for something completely different . . .
Using files Taken from notes by Dr. Neil Moore
Introduction to Programming
String and Lists Dr. José M. Reyes Álamo.
Introduction to Python: Day Three
Topics Designing a Program Input, Processing, and Output
CMSC201 Computer Science I for Majors Lecture 18 – String Formatting
functions: argument, return value
Presentation transcript:

Lakshit Dhanda

Output Formatting Python has ways to convert any value to a string. 2 Methods repr() – meant to generate representations of values read by the interpreter. str() – meant to return representation which are human readable. Values such as numbers or structures like lists and dictionaries, have the same representation using either function.

>>> s = 'Hello, world.' >>> str(s) 'Hello, world.' >>> repr(s) “ 'Hello, world.‘ " >>> str(1.0/7.0) ' ' >>> repr(1.0/7.0) ' '

The repr() of a string adds string quotes and backslashes: >>> hello = 'hello, world\n' >>> hellos = repr(hello) >>> print hellos 'hello, world\n' The argument to repr() may be any Python object. >>> repr((x, y, ('spam', 'eggs'))) "(32.5, 40000, ('spam', 'eggs'))"

str.rjust() method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left. str.rjust() There are similar methods str.ljust() and str.center().str.ljust()str.center() These methods do not write anything, they just return a new string. If the input string is too long, they don’t truncate it, but return it unchanged.

There is another method, str.zfill(), which pads a numeric string on the left with zeros. It understands about plus and minus signs.str.zfill() >>> '12'.zfill(5) '00012' >>> '-3.14'.zfill(7) ' '

str.format() is another function used to format the output. >>> print '{0} and {1}'.format('spam', 'eggs') spam and eggs A number in the brackets refers to the position of the object passed into the method. Positional and keyword arguments can be arbitrarily combined. >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg') The story of Bill, Manfred, and Georg.

'!s' (apply str()) and '!r' (apply repr()) can be used to convert the value before it is formatted.str()repr() >>> print 'The value of PI is approximately {!r}.'.format(math.pi) The value of PI is approximately An optional ':' and format specifier can follow the field name. Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making tables pretty.

Variable reference You can reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys. >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': } >>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ‘ 'Dcab: {0[Dcab]:d}’.format(table)) Jack: 4098; Sjoerd: 4127; Dcab:

Reading & Writing Files open() returns a file object, and is most commonly used with two arguments: open(filename, mode). open() Modes : r – read, w – write, a – append, r+ - both read and write. >>> f = open('/tmp/workfile', 'w') >>> print f

Methods of File Objects read(size) - reads some quantity of data and returns it as a string. Size is an optional numeric argument. readline() reads a single line from the file. write(string) writes the contents of string to the file, returning None. To write something other than a string, it needs to be converted to a string first.

tell() returns an integer giving the file object’s current position in the file, measured in bytes from the beginning of the file. Use seek(offset, from_what) to change the file object’s position. The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. from_what values : 0 - measures from the beginning of the file 1 uses the current file position 2 uses the end of the file as the reference point.

Pickle Module Python provides a standard module called pickle.pickle It can take almost any Python object and convert it to a string representation. This process is called pickling. Reconstructing the object from the string representation is called unpickling. If you have an object x, and a file object f that’s been opened for writing pickle.dump(x, f) To unpickle the object again, if f is a file object which has been opened for reading. x = pickle.load(f)