CHAPTER 2
■
DATA
TYPES AND REFERNCING
31
2
# Count occurrences of substrings
>>> state = 'Mississippi'
>>> state.count('ss')
2
# Partition a string returning a 3-tuple including the portion of string
# prior to separator, the separator
# and the portion of string after the separator
>>> x = "Hello, my name is Josh"
>>> x.partition('n')
('Hello, my ', 'n', 'ame is Josh')
# Assuming the same x as above, split the string using 'l'
as the separator
>>> x.split('l')
['He', '', 'o, my name is Josh']
# As you can see, the tuple returned does not contain the separator value
# Now if we add maxsplits value of 1, you can see that the right-most split is
# taken. If we specify maxsplits value of 2, the two right-most splits are taken
>>> x.split('l',1)
['He', 'lo, my name is Josh']
>>> x.split('l',2)
['He', '', 'o, my name is Josh']
String Formatting
You have many options when printing strings using the
print statement.
Much like the C programming
language, Python string formatting allows you to make use of a number of different conversion types
when printing.
Listing 2-5. Using String Formatting
# The two syntaxes below work the same
>>> x = "Josh"
>>> print "My name is %s" % (x)
My name is Josh
>>> print "My name is %s" % x
My name is Josh
# An example using more than one argument
>>> name = 'Josh'
>>> language = 'Python'
>>> print "My name is %s and I speak %s" % (name, language)
My name
is Josh and I speak Python
# And now for some fun, here's a different conversion type
# Mind you, I'm not sure where in the world the temperature would
# fluctuate so much!
>>> day1_temp = 65
>>> day2_temp = 68
www.it-ebooks.info
CHAPTER 2
■
DATA TYPES AND REFERNCING
32
>>> day3_temp = 84
>>> print "Given the temparatures %d, %d, and %d, the average would be %f" % (day1_temp,
day2_temp, day3_temp, (day1_temp + day2_temp + day3_temp)/3)
Given the temperatures 65, 68, and 83, the average would be 72.333333
Table 2-3 lists the conversion types.
Table 2-3. Conversion Types
Type Description
d
signed integer decimal
i
signed
integer
o
unsigned octal
u
unsigned decimal
x
unsigned hexidecimal (lowercase)
X
unsigned hexidecimal (uppercase letters)
E
floating point exponential format (uppercase 'E')
e
floating point exponential format (lowercase 'e')
f
floating point decimal format (lowercase)
F
floating point decimal format (same as 'f')
g
floating point exponential format if exponent < -4, otherwise float
G
floating point exponential format (uppercase) if exponent < -4, otherwise float
c
single character
r
string (converts any python object using repr())
s
string (converts any python object using str())
%
no conversion, results in a percent (%) character if specified twice
www.it-ebooks.info
CHAPTER 2
■
DATA TYPES AND REFERNCING
33
Listing 2-6.
>>> x = 10
>>> y = 5.75
>>> print 'The expression %d * %f results in %f' % (x, y, x*y)
The expression 10 * 5.750000 results in 57.500000
#
Example of using percentage
>>> test1 = 87
>>> test2 = 89
>>> test3 = 92
>>> "The gradepoint average of three students is %d%%" % (avg)
'The gradepoint average of three students is 89%'
Lists, Dictionaries, Sets, and Tuples
Lists, dictionaries, sets, and tuples all offer similar functionality and usability, but they each have their
own niche in the language. We’ll go through several examples of each since they all play an important
role under certain circumstances.
Unlike strings, all of the containers discussed in this section (except
tuples) are mutable objects, so they can be manipulated after they have been created.
Because these containers are so important, we’ll go through an exercise at the end of this chapter,
which will give you a chance to try them out for yourself.
Lists
Perhaps one of the most used constructs within the Python programming language is the list. Most other
programming languages provide similar containers for storing and manipulating data within an
application. The Python list provides an advantage over those similar constructs that are available in
statically typed languages. The dynamic tendencies of the Python language
help the list construct to
harness the great feature of having the ability to contain values of different types. This means that a list
can be used to store any Python data type, and these types can be mixed within a single list. In other
languages, this type of construct is often defined as a typed object, which locks the construct to using
only one data type.
The creation and usage of Python lists is just the same as the rest of the language. . .very simple and
easy to use. Simply assigning a set of empty square brackets to a variable creates an empty list. We can
also
use the built-in list() function to create a list. The list can be constructed and modified as the
application runs, they are not declared with a static length. They are easy to traverse through the usage
of loops, and indexes can also be used for positional placement or removal of particular items in the list.
We’ll start out by showing some examples of defining lists, and then go through each of the different
avenues which the Python language provides us for working with lists.
Listing 2-7. Defining Lists
# Define an empty list
my_list = []
my_list = list() # rarely used
#
Single Item List
>>> my_list = [1]
>>> my_list # note that there is no need to use print to display a variable in the
>>> #
interpreter
www.it-ebooks.info