The official home of the Python Programming Language
Python programming language object oriented web free open source software license documentation download community
Python Files I/O
Python Files I/O
This chapter will cover all the basic I/O functions available in Python. For more functions, please refer to standard Python documentation.
Printing to the Screen:
The simplest way to produce output is using theprint statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows:
#!/usr/bin/python
print "Python is really a great language,", "isn't it?";
This would produce the following result on your standard screen:
Python is really a great language, isn't it?
Reading Keyboard Input:
Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are:
raw_input
input
The raw_input Function:
The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).
#!/usr/bin/python
str = raw_input("Enter your input: ");
print "Received input is : ", str
This would prompt you to enter any string and it would display same string on the screen. When I typed "Hello Python!", its output is like this:
Enter your input: Hello Python
Received input is : Hello Python
The input Function:
The input([prompt]) function is equivalent toraw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.
#!/usr/bin/python
str = input("Enter your input: ");
print "Received input is : ", str
This would produce the following result against the entered input:
Enter your input: [x*5 for x inrange(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Opening and Closing Files:
Until now, you have been reading and writing to the standard input and output. Now, we will see how to play with actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do your most of the file manipulation using afile object.
The open Function:
Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.
Syntax:
file object = open(file_name [,access_mode][, buffering])
Here is paramters' detail:
file_name: The file_name argument is a string value that contains the name of the file that you want to access.
access_mode: The access_modedetermines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
Here is a list of the different modes of opening a file:
Modes
Description
r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+
Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
rb+
Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
The file object attributes:
Once a file is opened and you have one fileobject, you can get various information related to that file.
Here is a list of all attributes related to file object:
Attribute
Description
file.closed
Returns true if file is closed, false otherwise.
file.mode
Returns access mode with which file was opened.
file.name
Returns name of the file.
file.softspace
Returns false if space explicitly required with print, true otherwise.
Example:
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ",fo.softspace
This would produce the following result:
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method:
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
Syntax:
fileObject.close();
Example:
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
This would produce the following result:
Name of the file: foo.txt
Reading and Writing Files:
The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.
The write() Method:
The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string:
Syntax:
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example:
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.
Python is a great language.
Yeah its great!!
The read() Method:
The read() method reads a string from an open file. It is important to note that Python strings can have binary data and not just text.
Syntax:
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.
Example:
Let's take a file foo.txt, which we have created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This would produce the following result:
Read String is : Python is
File Positions:
The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. Thefrom argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.
Example:
Let's take a file foo.txt, which we have created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
This would produce the following result:
Read String is : Python is
Current file position : 10
Again read String is : Python is
Renaming and Deleting Files:
Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
The rename() Method:
The rename() method takes two arguments, the current filename and the new filename.
Syntax:
os.rename(current_file_name,new_file_name)
Example:
Following is the example to rename an existing file test1.txt:
#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
The remove() Method:
You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.
Syntax:
os.remove(file_name)
Example:
Following is the example to delete an existing file test2.txt:
#!/usr/bin/python
import os
# Delete file test2.txt
os.remove("text2.txt")
Directories in Python:
All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove and change directories.
The mkdir() Method:
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created.
Syntax:
os.mkdir("newdir")
Example:
Following is the example to create a directorytest in the current directory:
#!/usr/bin/python
import os
# Create a directory "test"
os.mkdir("test")
The chdir() Method:
You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.
Syntax:
os.chdir("newdir")
Example:
Following is the example to go into "/home/newdir" directory:
#!/usr/bin/python
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
The getcwd() Method:
The getcwd() method displays the current working directory.
Syntax:
os.getcwd()
Example:
Following is the example to give current directory:
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()
The rmdir() Method:
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.
Syntax:
os.rmdir('dirname')
Example:
Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory.
#!/usr/bin/python
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
File & Directory Related Methods:
There are three important sources, which provide a wide range of utility methods to handle and manipulate files & directories on Windows and Unix operating systems. They are as follows:
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
Python Decision Making
Python Decision Making
Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages:
Python programming language assumes anynon-zero and non-null values as true, and if it is either zero or null, then it is assumed as falsevalue.
Python programming language provides following types of decision making statements. Click the following links to check their detail.
Statement
Description
if statements
An if statement consists of aboolean expression followed by one or more statements.
if...else statements
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
nested if statements
You can use one if or else ifstatement inside another if orelse if statement(s).
Single Statement Suites:
If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.
Here is an example of a one-line if clause:
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
When the above code is executed, it produces the following result:
Value of expression is 100
Good bye!
Python Sending Email using SMTP
Python Sending Email using SMTP
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters:
host: This is the host running your SMTP server. You can specifiy IP address of the host or a domain name like tutorialspoint.com. This is optional argument.
port: If you are providing host argument, then you need to specify a port, where SMTP server is listening. Usually this port would be 25.
local_hostname: If your SMTP server is running on your local machine, then you can specify just localhost as of this option.
An SMTP object has an instance method calledsendmail, which will typically be used to do the work of mailing a message. It takes three parameters:
The sender - A string with the address of the sender.
The receivers - A list of strings, one for each recipient.
The message - A message as a string formatted as specified in the various RFCs.
Example:
Here is a simple way to send one e-mail using Python script. Try it once:
#!/usr/bin/python
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Here, you have placed a basic e-mail in message, using a triple quote, taking care to format the headers correctly. An e-mail requires a From,To, and Subject header, separated from the body of the e-mail with a blank line.
To send the mail you use smtpObj to connect to the SMTP server on the local machine and then use the sendmail method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren't always used to route mail).
If you're not running an SMTP server on your local machine, you can use smtplib client to communicate with a remote SMTP server. Unless you're using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider will have provided you with outgoing mail server details that you can supply them, as follows:
smtplib.SMTP('mail.your-domain.com', 25)
Sending an HTML e-mail using Python:
When you send a text message using Python, then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message.
While sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail.
Example:
Following is the example to send HTML content as an e-mail. Try it once:
#!/usr/bin/python
import smtplib
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Sending Attachments as an e-mail:
To send an e-mail with mixed content requires to set Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number, which can notappear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens.
Attached files should be encoded with thepack("m") function to have base64 encoding before transmission.
Example:
Following is the example, which will send a file/tmp/test.txt as an attachment. Try it once:
#!/usr/bin/python
import smtplib
import base64
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send anattachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename,encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"
Python Regular Expressions
Python Regular Expressions
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression.
We would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings asr'expression'.
The match Function
This function attempts to match RE pattern tostring with optional flags.
Here is the syntax for this function:
re.match(pattern, string, flags=0)
Here is the description of the parameters:
Parameter
Description
pattern
This is the regular expression to be matched.
string
This is the string, which would be searched to match the pattern at the beginning of string.
flags
You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.
The re.match function returns a match object on success, None on failure. We would usegroup(num) or groups() function of match object to get matched expression.
Match Object Methods
Description
group(num=0)
This method returns entire match (or specific subgroupnum)
groups()
This method returns all matching subgroups in a tuple (empty if there weren't any)
Example:
#!/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
print "matchObj.group() : ",matchObj.group()
print "matchObj.group(1) : ",matchObj.group(1)
print "matchObj.group(2) : ",matchObj.group(2)
else:
print "No match!!"
When the above code is executed, it produces following result:
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
The search Function
This function searches for first occurrence of REpattern within string with optional flags.
Here is the syntax for this function:
re.search(pattern, string, flags=0)
Here is the description of the parameters:
Parameter
Description
pattern
This is the regular expression to be matched.
string
This is the string, which would be searched to match the pattern anywhere in the string.
flags
You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.
The re.search function returns a match object on success, None on failure. We would usegroup(num) or groups() function of match object to get matched expression.
Match Object Methods
Description
group(num=0)
This method returns entire match (or specific subgroupnum)
groups()
This method returns all matching subgroups in a tuple (empty if there weren't any)
Example:
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
print "searchObj.group() : ",searchObj.group()
print "searchObj.group(1) : ",searchObj.group(1)
print "searchObj.group(2) : ",searchObj.group(2)
else:
print "Nothing found!!"
When the above code is executed, it produces following result:
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
Matching vs Searching:
Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, whilesearch checks for a match anywhere in the string (this is what Perl does by default).
Example:
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line,re.M|re.I)
if matchObj:
print "match --> matchObj.group() : ", matchObj.group()
else:
print "No match!!"
searchObj = re.search( r'dogs', line,re.M|re.I)
if searchObj:
print "search --> searchObj.group() : ", searchObj.group()
else:
print "Nothing found!!"
When the above code is executed, it produces the following result:
No match!!
search --> matchObj.group() : dogs
Search and Replace:
Some of the most important re methods that use regular expressions is sub.
Syntax:
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the REpattern in string with repl, substituting all occurrences unless max provided. This method would return modified string.
Example:
Following is the example:
#!/usr/bin/python
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num
# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print "Phone Num : ", num
When the above code is executed, it produces the following result:
Phone Num : 2004-959-559
Phone Num : 2004959559
Regular-expression Modifiers - Option Flags
Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these:
Modifier
Description
re.I
Performs case-insensitive matching.
re.L
Interprets words according to the current locale. This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior (\b and \B).
re.M
Makes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).
re.S
Makes a period (dot) match any character, including a newline.
re.U
Interprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B.
re.X
Permits "cuter" regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treatsunescaped # as a comment marker.
Regular-expression patterns:
Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash.
Following table lists the regular expression syntax that is available in Python:
Pattern
Description
^
Matches beginning of line.
$
Matches end of line.
.
Matches any single character except newline. Using m option allows it to match newline as well.
[...]
Matches any single character in brackets.
[^...]
Matches any single character not in brackets
re*
Matches 0 or more occurrences of preceding expression.
re+
Matches 1 or more occurrence of preceding expression.
re?
Matches 0 or 1 occurrence of preceding expression.
re{ n}
Matches exactly n number of occurrences of preceding expression.
re{ n,}
Matches n or more occurrences of preceding expression.
re{ n, m}
Matches at least n and at most m occurrences of preceding expression.
a| b
Matches either a or b.
(re)
Groups regular expressions and remembers matched text.
(?imx)
Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?-imx)
Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?: re)
Groups regular expressions without remembering matched text.
(?imx: re)
Temporarily toggles on i, m, or x options within parentheses.
(?-imx: re)
Temporarily toggles off i, m, or x options within parentheses.
(?#...)
Comment.
(?= re)
Specifies position using a pattern. Doesn't have a range.
(?! re)
Specifies position using pattern negation. Doesn't have a range.
(?> re)
Matches independent pattern without backtracking.
\w
Matches word characters.
\W
Matches nonword characters.
\s
Matches whitespace. Equivalent to [\t\n\r\f].
\S
Matches nonwhitespace.
\d
Matches digits. Equivalent to [0-9].
\D
Matches nondigits.
\A
Matches beginning of string.
\Z
Matches end of string. If a newline exists, it matches just before newline.
\z
Matches end of string.
\G
Matches point where last match finished.
\b
Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\B
Matches nonword boundaries.
\n, \t, etc.
Matches newlines, carriage returns, tabs, etc.
\1...\9
Matches nth groupedsubexpression.
\10
Matches nth groupedsubexpression if it matched already. Otherwise refers to the octal representation of a character code.
Regular-expression Examples
Literal characters:
Example
Description
python
Match "python".
Character classes:
Example
Description
[Pp]ython
Match "Python" or "python"
rub[ye]
Match "ruby" or "rube"
[aeiou]
Match any one lowercase vowel
[0-9]
Match any digit; same as [0123456789]
[a-z]
Match any lowercase ASCII letter
[A-Z]
Match any uppercase ASCII letter
[a-zA-Z0-9]
Match any of the above
[^aeiou]
Match anything other than a lowercase vowel
[^0-9]
Match anything other than a digit
Special Character Classes:
Example
Description
.
Match any character except newline
\d
Match a digit: [0-9]
\D
Match a nondigit: [^0-9]
\s
Match a whitespace character: [ \t\r\n\f]
\S
Match nonwhitespace: [^ \t\r\n\f]
\w
Match a single word character: [A-Za-z0-9_]
\W
Match a nonword character: [^A-Za-z0-9_]
Repetition Cases:
Example
Description
ruby?
Match "rub" or "ruby": the y is optional
ruby*
Match "rub" plus 0 or more ys
ruby+
Match "rub" plus 1 or more ys
\d{3}
Match exactly 3 digits
\d{3,}
Match 3 or more digits
\d{3,5}
Match 3, 4, or 5 digits
Nongreedy repetition:
This matches the smallest number of repetitions:
Example
Description
<.*>
Greedy repetition: matches "<python>perl>"
<.*?>
Nongreedy: matches "<python>" in "<python>perl>"
Grouping with parentheses:
Example
Description
\D\d+
No group: + repeats \d
(\D\d)+
Grouped: + repeats \D\d pair
([Pp]ython(, )?)+
Match "Python", "Python, python, python", etc.
Backreferences:
This matches a previously matched group again:
Example
Description
([Pp])ython&\1ails
Match python&pails orPython&Pails
(['"])[^\1]*\1
Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc.
Alternatives:
Example
Description
python|perl
Match "python" or "perl"
rub(y|le))
Match "ruby" or "ruble"
Python(!+|\?)
"Python" followed by one ormore ! or one ?
Anchors:
This needs to specify match position.
Example
Description
^Python
Match "Python" at the start of a string or internal line
Python$
Match "Python" at the end of a string or line
\APython
Match "Python" at the start of a string
Python\Z
Match "Python" at the end of a string
\bPython\b
Match "Python" at a word boundary
\brub\B
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
Python(?=!)
Match "Python", if followed by an exclamation point
Python(?!!)
Match "Python", if not followed by an exclamation point
Special syntax with parentheses:
Example
Description
R(?#comment)
Matches "R". All the rest is a comment
R(?i)uby
Case-insensitive while matching "uby"
R(?i:uby)
Same as above
rub(?:y|le))
Group only without creating \1backreference
Python Object Oriented
Python Object Oriented
Python has been an object-oriented language from day one. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.
If you don't have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.
However, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed:
Overview of OOP Terminology
Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables aren't used as frequently as instance variables are.
Data member: A class variable or instance variable that holds data associated with a class and its objects.
Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects (arguments) involved.
Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
Inheritance : The transfer of the characteristics of a class to other classes that are derived from it.
Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.
Instantiation : The creation of an instance of a class.
Method : A special kind of function that is defined in a class definition.
Object : A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.
Operator overloading: The assignment of more than one function to a particular operator.
Creating Classes:
The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows:
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed viaClassName.__doc__.
The class_suite consists of all the component statements defining class members, data attributes and functions.
Example:
Following is the example of a simple Python class:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" %Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
The variable empCount is a class variable whose value would be shared among all instances of a this class. This can be accessed as Employee.empCount from inside the class or outside the class.
The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you don't need to include it when you call the methods.
Creating instance objects:
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
Accessing attributes:
You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows:
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" %Employee.empCount
Now, putting all the concepts together:
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" %Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" %Employee.empCount
When the above code is executed, it produces the following result:
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
You can add, remove or modify attributes of classes and objects at any time:
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.
Instead of using the normal statements to access attributes, you can use following functions:
The getattr(obj, name[, default]) : to access the attribute of object.
The hasattr(obj,name) : to check if an attribute exists or not.
The setattr(obj,name,value) : to set an attribute. If attribute does not exist, then it would be created.
The delattr(obj, name) : to delete an attribute.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'
Built-In Class Attributes:
Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute:
__dict__ : Dictionary containing the class's namespace.
__doc__ : Class documentation string or None if undefined.
__name__: Class name.
__module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode.
__bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
For the above class let's try to access all these attributes:
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" %Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
print "Employee.__doc__:",Employee.__doc__
print "Employee.__name__:",Employee.__name__
print "Employee.__module__:",Employee.__module__
print "Employee.__bases__:",Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
When the above code is executed, it produces the following result:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <functiondisplayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
Destroying Objects (Garbage Collection):
Python deletes unneeded objects (built-in types or class instances) automatically to free memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed garbage collection.
Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.
An object's reference count increases when it's assigned a new name or placed in a container (list, tuple or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.
a = 40 # Create object <40>
b = a # Increase ref. count of<40>
c = [b] # Increase ref. count of<40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of<40>
c[0] = -1 # Decrease ref. count of <40>
You normally won't notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any nonmemory resources used by an instance.
Example:
This __del__() destructor prints the class name of an instance that is about to be destroyed:
#!/usr/bin/python
class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name =self.__class__.__name__
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result:
3083401324 3083401324 3083401324
Point destroyed
Note: Ideally, you should define your classes in separate file, then you should import them in your main program file using import statement. Kindly check Python - Modules chapter for more details on importing modules and classes.
Class Inheritance:
Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.
Syntax:
Derived classes are declared much like their parent class; however, a list of base classes to inherit from are given after the class name:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
Example:
#!/usr/bin/python
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :",Parent.parentAttr
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
When the above code is executed, it produces the following result:
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
Similar way, you can drive a class from multiple parent classes as follows:
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....
You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.
The issubclass(sub, sup) booleanfunction returns true if the given subclasssub is indeed a subclass of the superclasssup.
The isinstance(obj, Class) booleanfunction returns true if obj is an instance of class Class or is an instance of a subclass of Class
Overriding Methods:
You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.
Example:
#!/usr/bin/python
class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # define child class
def myMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.myMethod() # child calls overridden method
When the above code is executed, it produces the following result:
Calling child method
Base Overloading Methods:
Following table lists some generic functionality that you can override in your own classes:
SN
Method, Description & Sample Call
1
__init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)
2
__del__( self )
Destructor, deletes an object
Sample Call : del obj
3
__repr__( self )
Evaluatable string representation
Sample Call : repr(obj)
4
__str__( self )
Printable string representation
Sample Call : str(obj)
5
__cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
Overloading Operators:
Suppose you've created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.
You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation:
Example:
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a,self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
When the above code is executed, it produces the following result:
Vector(7,8)
Data Hiding:
An object's attributes may or may not be visible outside the class definition. For these cases, you can name attributes with a double underscore prefix, and those attributes will not be directly visible to outsiders.
Example:
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
When the above code is executed, it produces the following result:
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class name. You can access such attributes asobject._className__attrName. If you would replace your last line as following, then it would work for you:
.........................
printcounter._JustCounter__secretCount
When the above code is executed, it produces the following result:
1
2
2
Python Exceptions Handling
Python Exceptions Handling
Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them:
Exception Handling: This would be covered in this tutorial. Here is a list standard Exceptions available in Python:Standard Exceptions.
Assertions: This would be covered inAssertions in Python tutorial.
What is Exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it can't cope with, it raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it would terminate and come out.
Handling an exception:
If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.
Syntax:
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above-mentioned syntax:
A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
Example:
Here is simple example, which opens a file and writes the content in the file and comes out gracefully because there is no problem at all:
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
This will produce the following result:
Written content in the file successfully
Example:
Here is one more simple example, which tries to open a file where you do not have permission to write in the file, so it raises an exception:
#!/usr/bin/python
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
This will produce the following result:
Error: can't find file or read data
The except clause with no exceptions:
You can also use the except statement with no exceptions defined as follows:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.
The except clause with multiple exceptions:
You can also use the same except statement to handle multiple exceptions as follows:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
The try-finally clause:
You can use a finally: block along with a try:block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note that you can provide except clause(s), or a finally clause, but not both. You can not use elseclause as well along with a finally clause.
Example:
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will produce the following result:
Error: can't find file or read data
Same example can be written more cleanly as follows:
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes to the finallyblock. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.
Argument of an Exception:
An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows:
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you are writing the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.
This variable will receive the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.
Example:
Following is an example for a single exception:
#!/usr/bin/python
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz");
This would produce the following result:
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
Raising an exceptions:
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement.
Syntax:
raise [Exception [, args [,traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.
Example:
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows:
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write our except clause as follows:
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
User-Defined Exceptions:
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed fromRuntimeError. This is useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise your exception as follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
Python Variable Types
Python Variable Types
Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.
Assigning Values to Variables:
Python variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example:
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles and name variables, respectively. While running this program, this will produce the following result:
100
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously. For example:
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c.
Standard Data Types:
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard types that are used to define the operations possible on them and the storage method for each of them.
Python has five standard data types:
Numbers
String
List
Tuple
Dictionary
Python Numbers:
Number data types store numeric values. They are immutable data types which means that changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example:
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is:
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example:
del var
del var_a, var_b
Python supports four different numerical types:
int (signed integers)
long (long integers [can also be represented in octal and hexadecimal])
float (floating point real values)
complex (complex numbers)
Examples:
Here are some examples of numbers:
int
long
float
complex
10
51924361L
0.0
3.14j
100
-0x19323L
15.20
45.j
-786
0122L
-21.9
9.322e-36j
080
0xDEFABCECBDAECBFBAEl
32.3+e18
.876j
-0490
535633629843L
-90.
-.6545+0J
-0x260
-052318172735L
-32.54e100
3e+26J
0x69
-4721885298529L
70.2-E12
4.53e-7j
Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.
Python Strings:
Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.
The plus ( + ) sign is the string concatenation operator and the asterisk ( * ) is the repetition operator. For example:
#!/usr/bin/python
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
This will produce the following result:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists:
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator. For example:
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
This will produce the following result:
['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
Python Tuples:
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-onlylists. For example:
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
This will produce the following result:
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
Following is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists:
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
Python Dictionary:
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed using square braces ( [] ). For example:
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
This will produce the following result:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.
Data Type Conversion:
Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.
Function
Description
int(x [,base])
Converts x to an integer. basespecifies the base if x is a string.
long(x [,base] )
Converts x to a long integer. basespecifies the base if x is a string.
float(x)
Converts x to a floating-point number.
complex(real [,imag])
Creates a complex number.
str(x)
Converts object x to a string representation.
repr(x)
Converts object x to an expression string.
eval(str)
Evaluates a string and returns an object.
tuple(s)
Converts s to a tuple.
list(s)
Converts s to a list.
set(s)
Converts s to a set.
dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s)
Converts s to a frozen set.
chr(x)
Converts an integer to a character.
unichr(x)
Converts an integer to a Unicode character.
ord(x)
Converts a single character to its integer value.
hex(x)
Converts an integer to a hexadecimal string.
oct(x)
Converts an integer to an octal string.