In this chapter, we'll cover operators and string formatting. Python
string formatting controls the creation of strings. Done correctly, it makes the
production of these strings simple and straightforward.

I've said it before, and I'll say it again: If you're a
beginning programmer, remember that the only way to learn programming is by
programming, so try to follow along with the interactive sessions throughout the
chapter. The interactive interpreter mode will give you a hands-on understanding
of Python operators and string formatting. If you have trouble with an Advanced
Topic section, just skim over it; don't let it slow you down.

As in Chapter 2, most of the concepts in this chapter act as building blocks
for more complex ideas. Don't worry if something seems unclear to you at
this point; you might understand it later, in a different context. For example,
logical and comparison operators may not be easily grasped here, but wait until
Chapter 4, where we deal with the if statement, which makes frequent use of
these operators and so should clear things up.

If you've programmed before, most of this chapter will be familiar. For
example, operators and string formatting in Python and C are very similar. If
you have in-depth programming experience, you can probably just skim this
material, especially if you're comfortable with C, Java, and/or Visual
Basic. Do, however, pay attention to the following sections:

"Arithmetic with Strings, Lists, and Tuples"

"% Tuple String Formatting"

"Advanced Topic: Using the %d, %i, %f, and %e Directives for
Formatting Numbers"

Also read the "For Programmers" sidebar (see pages 5051).

Operators

Recall from Chapter 2 our definition of expressions as simple statements that
return a value. In Python, many expressions use operators, such as +, , *,
and =. The following subsections describe each operator type, and each section
contains a table of the type's operators along with sample interactive
sessions illustrating their use. If you feel as if you've been this way
before, you havewe've been using operators since Chapter 1.

Arithmetic Operators

Arithmetic operators work with the numeric types Float, Int, and Long. Table
31 describes them, including three we have yet to encounter: modulus (%),
which gives the remainder; exponential (**), which raises one number to the
power of another number; and abs, which gives a number's absolute value.

One example of modulus is 3/2, which gives the remainder of 1 ( 3
/ 2 = 1 1 / 2 ). Another is 10/7, which
gives a remainder of 3 ( 10 / 7 = 1 3 / 7
). In Python, we express the previous sentence as

>>> 10 % 7 3 >>> 3 % 2 1 >>>

Once you understand modulus, the divmod() function, which we'll discuss
in a later chapter, should come easily to you.

Does both of the division operators at once and returns a tuple; the second
item in the tuple contains the remainder. divmod(x,y) is equivalent to
x/y,x%y

This:

>>> divmod (10,3)

(3, 1)

Is the same as this:

>>> 10/3,10%3

(3, 1)

This:

>>> divmod (5,2)

(2, 1)

Is the same as this:

>>> 5/2, 5%2

(2, 1)

abs

Finds the absolute value of a number

>>> abs(100)

100

>>> abs(-100)

100

-,

Sign

>>> 1, -1, +1, +-1

(1, -1, 1, -1)

Numeric Conversion Operators

Many times we need to convert from one numeric type to another. The three
operators that perform this conversion are Int(x), Long(x), and Float(x), where
x is any numeric value. To illustrate, in the example that follows we create
three numeric types: 1 (Long), f (Float), and i (Integer).

>>> l,f,i=1L, 1.0, 1

The output is

>>> l,f,i
(1L, 1.0, 1)

The next three examples in turn convert i to Float, f and i to Long, and l
and f to Integer.

Logical Operators, Comparison Operators, and Boolean Values

Logical operators are a way to express choices, such as "This one and
that one or that one but not this one." Comparison
operators are a way to express questions, such as "Is this one greater
than that one?" Both work with Boolean values, which express the answer
as either true or false. Unlike Java, Python has no true Boolean type. Instead,
as in C, its Booleans can be numeric values, where any nonzero value must be
true and any zero value must be false. Thus, Python interprets as false the
following values:

None

Empty strings

Empty tuples

Empty lists

Empty dictionaries

Zero

and as true all other values, including

Nonempty strings

Nonempty tuples

Nonempty lists

Nonempty dictionaries

Not zero

Table 32 describes the logical operators. They return 1 for a true
expression and 0 for a false expression. Table 33 describes the comparison
operators. They return some form of true for a true expression and some form of
false for a false expression.

Logical and comparison operators often work together to define application
logic (in English, application logic simply means decision making).When they do,
they're often used with if and while statements. Don't worry
about if and while just yet; we'll get into them in detail in Chapter 4.
For now, a simple way to visualize them is to imagine that you like vanilla and
chocolate ice cream but hate nuts, and you want to express your preference in a
way that Python will understand, like this:

Now the num variable is equivalent to a list containing one element, but this
isn't exactly what we want. However, since this code is returning a list,
we can put the entire expression to the left of the assignment operator in
parentheses, which will achieve our desired result.

>>> num = ((5 > 3 and [true_return]) or [false_return])[0]
>>> num
0

To sum up, Python's bulletproof equivalent of the conditional operator
is

val = ((boolean_test and [true_return]) \
or [false_return])[0]

which is no more verbose than another Python expression:

if (boolean_test): val = true_return
else: val = false_return

Python's version of the conditional operator is hard to understand and
use, so go easy with it. Perhaps one day Python will have a conditional operator
of its own (and, I might add, its own += operator).

Advanced Topic: Bitwise and Shift Operators

If you lack experience with any programming language or with Boolean algebra,
you should ignore bitwise operators. Another reason to ignore them is that
they're usually associated with low-level programming, and you're
learning Python, which is much higher level than C, C++, or even Java. If for
some reason you're curious about bitwise operators, any introductory C text
will tell you all you need to know. The same goes for shift operators.

Just for the sake of completeness, Table 34 describes both operator
types. To understand it, you need to know something of hexadecimal and Boolean
algebra. (See Chapter 10 for an example of a hexdump file viewer, which uses the
shift operators.)

Operator Precedence

Operator precedence determines the order in which Python evaluates the parts
of a statement. It generally follows the operator precedence you learned in high
school algebra and is nearly identical to that used in any other common
programming language. Here's an example in which y/z is processed before 2
+ y, rendering x equal to 4 and not 6.

>>> x,y,z=1,4,2
>>> x = 2 + y / z
>>> x
4

When in doubt as to which operator will be evaluated first, use parentheses.
They prevent many a mistake if you use them to force precedence, and they
enhance code readability.

You may occasionally want to force a precedence other than the algebraic
default to make it more explicit. The following example shows how to do this:

>>> x,y,z = 1,4,2
>>> x = 2 + (y/z)
>>> x
4

>>> x = (2+y) /z
>>> x
3

The choice of precedence here depends on which expression2 + y or
y/zis to be evaluated first. Note, though, that the value of x changes
according to the grouping and ends up as either 4 or 3. The first expression, 2
+ y/z, is unnecessary except to adorn the code with parentheses for clarity,
which is important for code maintainability.

Visit www.python.org for a detailed description of operator
precedence. For now, the following list shows all operators in their precedence
order:

[], (), {}, '

Parentheses, string conversion

seq[index]

Indexing sequences or dictionaries

integer

.MAX_INT Attribute reference

~I

Bit inversion

-i, +i

Unary minus, unary plus

*, /, %

Multiplication, division, modulus

+, -

Addition, subtraction

Table 34 Bitwise and Shift Operators

Operator

Description

Interactive Session

<<

Shift left

>>> # binary 1111 1111

>>> x = 0xff

>>> # z = 0011 1111 1100

>>> z = x << 2

>>> print (x)

255

>>> print (z)

1020

>>

Shift right

>>> # z = 1020

>>> #z = 1111 1111

>>> z = z >> 2

>>> z

255

&

Bitwise and

>>> # y = binary 0000 1010

>>> y = 0x0A

>>> print (y)

10

>>> print (x)

255

>>> z = y & z

>>> print (z)

10

|

Bitwise or

>>> #continued example

>>> z = y | x

>>> print (z)

255

^

Bitwise XOR

>>> z = y ^ x

>>> z

245

~

Bitwise not

>>> y = 0xffffffff

>>> y

-1

>>> z = ~y

>>> z

0

<<,>>

Bit shifting, left and right

[bar], &, ^

Bitwise operator or, and, XOR

<, >, >=, <=, ==, is not,

Comparison operators

is, !=, <>, in, not in

not

Logical not

and

Logical and

or

Logical or

Arithmetic with Strings, Lists, and Tuples

As in Java, the addition operator (+) in Python works with string types to
concatenate, that is, link strings. (Recall that we used + on strings in Chapter
1.) Unlike in Java, the multiplication operator (*) in Python is used to repeat
string values. Consider the following interactive session:

In the first line, we concatenate the string "I love my family"
with the string "very" multiplied by 4, which gives "very very
very very". If we want to sign our letter with hugs and kisses (Xs and Os),
we can multiply to save time in a similar way.