- Getting Started with Python and Raspberry Pi
- Dan Nixon
- 2683字
- 2021-07-16 19:36:33
Data in Python
Before jumping to the various data types that are available in Python, it is worth noting that Python is a strong dynamically typed programming language, which means both that:
- Once a variable (a unit of stored data in a program) has been given a value, its type is set and will not change until the variable is assigned a value of a different type (strong)
- A variable can hold a value of any type as the type is given by the value, not the variable itself (dynamic)
This is best explained with an example that can be executed from the interactive console, assuming we have a variable representing a string:
flan = "flan"
We can query the value held by the variable and the type using the following code (note that this will only work on an interactive console as return values are automatically printed to the terminal):
flan type(flan)
As the following output shows, the variable is of type str
which represents a string in Python:

We can now reassign the variable to a new numerical value and check the type as done earlier:
flan = 495 flan type(flan)
Now when we check the type, we see the type has changed to type int
, the type used to store an integer value.

You can also use the isinstance()
function to test if a variable holds a value of a given type, as demonstrated in the following image:

Certain types can be converted by using the type name as a function, as shown in the following example:
flan = "495" flan type(flan) flan_i = int(flan) flan_i type(flan_i)
As the output shows, this converts the original value of the flan
variable to an integer based on the contents of the string:

Numerical types
Python has several different numerical types built in that allow you to represent integer, floating point, and complex numbers using the following types:
There are a range of ways to define a numerical value in Python. Typically, this can be done by typing the standard representation of a number as shown in the following example:
a = 42 type(a) b = 0.009 type(b) c = 10000000000 type(c) d = 100L type(d)
Following is the output of this code:

As the output shows, each numerical value is assigned a different type in Python:
- Since the value of
a
is less than the maximum precision of the system,int
is used b
usesfloat
as its value is a decimal numberc
useslong
as its value is greater than the maximum precision of the system- Finally,
d
useslong
as addingL
to the end of an integer number explicitly makes it along
type
Since we have mentioned the maximum numerical precision of a particular system, we will quickly look at how we can actually find out what the value of this is. Python provides this value in the sys
module (which is used to retrieve information about the host system).
import sys sys.maxint
This returns the maximum value that can be held as an int,
as shown in the following screenshot; anything larger will use the long
type instead:

Integer types can also be defined using hexadecimal and binary notation using the 0x
and 0b
prefixes, as shown in the following example:
e = 0xFF e type(e) f = 0b11111111 f type(f)
As the following screenshot shows, both numbers evaluate to an integer with the value 255:

Using this format for integer types will become more useful later when we start interacting with the GPIO expansion header on the Raspberry Pi.
Floating point and complex numbers also have their own syntax, based on the standard scientific syntax for their notation.
g = 2.75e-3 g type(g) h = (5+3j) h type(h)
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
This creates a floating point and complex number respectively, as shown in the following output:

It is also possible to create numerical types explicitly using the type name as a function, as shown in the following example. Doing this also allows you to convert between different numerical types and create numerical types by parsing strings.
a = int(4) a type(a) b = int("4") b type(b) c = long(4) c type(c) d = int(5.9864) d type(d) e = float(9) e type(e) f = complex(3, 8) f type(f) g = int("one")
The output from this previous example is shown in the following screenshot. Note that for the last variable (g
), an exception was raised as there was no way to convert the string to an int
type (we will cover exceptions in more detail later on in the chapter).

Operations on numerical types
If you have ever used any other programming language then the numerical operators you will find in Python will not be greatly different. The main operators are listed as follows:
x + y
: Returns the value of the addition ofx
andy
x - y
: Returns the value ofy
subtracted fromx
x * y
: Returns the product ofx
andy
x / y
: Returns the quotient ofx
andy
x // y
: Returns the integer quotient ofx
andy
(integer division)x % y
: Returns the remainder ofx // y
(modulo)abs(x)
: Returns the absolute value ofx
(that is, removes the negative sign)divmod(x, y)
: Returnstuple
containingx // y
andx % y
(we will look at thetuple
type in more detail in the next chapter)x ** y
orpow(x, y)
: Returnsx
to the powery
It is worth noting that with the exception of complex numbers, which do not work for integer division, module, and the divmod()
operations, you can use any combination of numerical types with these functions.
Following is an example of these operations:
a = 49 b = 5 c = 6.5 d = 3e-9 e = 100L a + b a - b a / b a // b a % b c / d e / a div, rem = divmod(a, b) div rem
The output of this preceding code is shown next. You may wish to use the type()
functions here to check the return type of each of the operations.

One thing to note here is that despite the fact that 49/5 is actually 9.8, when we execute 49/5
in Python, the result will be 9. Because both operands are of type int
only integer division was performed and hence the return value will effectively be the floored value (that is, the value with the decimal part subtracted) of the actual result.
It is also possible to perform certain operations directly on the left hand side value of the operation. In this case, the value held by the left hand side is modified and no value is returned. This is supported by the following operations:
+
, becomesa += b
-
, becomesa -= b
*
, becomesa *= b
/
, becomesa /= b
//
, becomesa //= b
%
, becomesa %= b
**
, becomesa **= b
The following example demonstrates this format for the operators. Note that here you need to print out the output in order to see that the value is being changed.
a = 45 b = 5 a += b a a -= b a a *= b a a /= b a
The output of this is shown in the following screenshot:

Note
While the standard Python functions provide most numerical operations that you are likely to need, the SciPy package has a lot of tools that are better suited to working with large amounts of numerical data. Refer to www.scipy.org for more details.
String manipulation
The next topic we will look at is string storage and manipulation. As with numerical types, strings can be assigned using a literal (a value written exactly as it should be interpreted) as the right hand operand of the assignment operator =.
You can also take a majority of any other type and convert it to a string using the str()
function as shown in the following example:
a = "Hello, world!" a type(a) b = complex(3, 6) b type(b) c = str(b) c type(c)
The output of this is shown in the following screenshot:

There are a large number of functions for performing manipulation and searching on a string object in Python. Here we will have a quick look at some of the more common and useful ones. The full list is available online at docs.python.org/2/library/stdtypes.html#string-methods.
Following is a list of the most common string manipulation functions and a quick example of how they are used:
capitalize
: This returns a copy of the string with the first character capitalized and the remaining characters in lower case. For example:"hello, world".capitalize()
This example would return the string
'Hello, world'
, as shown in the following output:lower
: This returns a copy of the string with all the characters converted to lower case. For example:"Hello World".lower()
This example would return the string
"hello world"
as shown in the following output:upper
: This returns a copy of the string with all the characters converted to upper case. For example:"Hello World".upper()
This example would return the string
"HELLO WORLD"
as shown in the following output:find
: This returns the first index in the string where a substring is found, or -1 if the substring is not found. Optionally, limits can also be provided to specify the search range. For example:"The quick brown fox".find("brown") "The quick brown fox".find("green") "the quick brown fox jumps over the lazy dog".find("the", 5)
The output of this example is shown in the following screenshot. Note how the second search failed and returned
-1,
and the third returned the index of the second"the"
rather than the first as the search only began at the 5th character.replace
: This replaces a given substring with a replacement string, optionally stopping after a given number of replacements have been done. For example:"She sells seashells by the seashore".replace("sea", "ocean") "She sells seashells by the seashore".replace("sea", "ocean", 1)
As the following screenshot shows, the first example replaces all occurrences of
"sea"
with"ocean"
; in the second example, only the first occurrence was changed as a limit of 1 replacement was specified.strip
: This removes excess whitespace characters from the start and end of a string (leaving whitespace inside the string untouched) and returns the new string. For example:" Hello, world ! ".strip()
Here, the string
"Hello, world !"
is returned as shown in the following output:split
: This splits a string on a given delimiter up to an optional maximum number of times returning a list of the new strings. If the delimiter is not found then a single string will be returned. For example:"Eggs, Milk, Bread".split(", ") "Eggs, Milk, Bread".split(", ", 1) "Eggs, Milk, Bread".split("\t")
As the following screenshot of the output shows, the first example splits each of the items into its own string, the second stops after it has performed one split, and the third returns a single string as the delimiter (
\t
is the escape sequence for the Tab key) was not found in the string:in
: This determines if a string contains a given substring. For example:"Bread" in "Eggs, Milk, Bread" "Butter" in "Eggs, Milk, Bread"
Each expression evaluates to a boolean (a value that can either be true or false), as shown in the following output:
Note that a lot of these functions are called by adding the function to the end of the string itself. This is because in Python strings are what are known as objects (collections of data and functions that represent a part of a system). We will see this in more detail later on in the book.
Python supports both the conventional style string formatting using the %
identifier syntax (for example, %.5d
is an integer with up to 5 leading zeros) which can be found in a lot of other programming languages, and Python's own (more powerful) string formatting mini-language.
Here we will only look at the conventional style formatting as it is usually good enough for the majority of uses and is much simpler to understand. The details for the Python formatting language can be found online at docs.python.org/2/library/string.html#string-formatting.
The conventional string formatting is done in Python using the syntax in the following example:
"%s is %d years old" % ("Alice", 23)
This returns the string "Alice is 23 years old",
as shown in the following output:

There are several additional formatting options that can be used here to control how the string is formatted. The complete documentation can be found online at docs.python.org/2/library/stdtypes.html#string-formatting-operations.
A format string is made up of several sections as follows:
%[(name)][flags][minimum width][.precision][length]type
name
: This allows you to optionally specify the name of the key that is used to take the value fromflags
: This is used to control the type of conversion performedminimum width
: This is used to pad out the value so that the string is a certain number of characters longprecision
: This is used to specify the precision of the numerical typeslength
: This allows you to modify the length of the numerical typestype
: This is the character representing the data type of the parameter
Following is a list of the most common data types:
s
: Stringi
: Integer numberf
: Floating point number
String templates are very similar to string formatting. However, they use customized $
marked substitutions that rely less on the type of the variable being used for the substitution.
Templates are available via the Template
class in the string
module.
The following is a simple example of how templates can be used to format multiple strings:
from string import Template hello_template = Template("Hello $name, welcome to Python!") hello_template.substitue(name="Alice") hello_template.substitue(name="Marisa") hello_template.substitue(name="Reimu")
This example gives the following output on the interactive terminal:

It is worth noting that the type of the parameter passed to the substitute
function is not really that important as it will be converted to a string in order to be substituted into the template string. The following is an example of this:
from string import Template t = Template("The number is $number") t.substitute(number="one") t.substitute(number=42) t.substitute(number=100L) t.substitute(number=4e-3) t.substitute(number=(3+6j))
In the following screenshot, you will see that the output of each substitution simply gives whatever the standard string representation of each number is:

So far, we have just been using keyword arguments (by passing an argument to the substitute
function by name) to provide the substitutions to the template. However, it is also possible to provide a dictionary containing the values (we will be covering dictionaries in more detail in the next chapter), as in the following example:
from string import Template t = Template("$person_a says $something to $person_b") info = {"person_a": "Marisa", "something": "hello", "person_b": "Alice"} t. substitute(info)
This is equivalent to providing the values as parameters to substitute
and will provide the following output:

One issue with using substitute
to perform the replacement is that an exception is raised if one of the substitution parameters is missing. Depending on the application, this may or may not be the desired behavior, but for cases where the call should not fail, there is the safe_substitute
function which will never raise an exception. This is shown with the following example:
from string import Template t = Template("$person_a says hello to $person_b") t.substitute(person_a="Mima") t.safe_substitute(person_a="Mima")
As shown in the following output, the first substitution fails as the person_b
parameter is missing. However, when safe_substitute
is used instead, the substitution completes but skips replacing the template parameter in the template string with anything.

- DevOps with Kubernetes
- Rust實(shí)戰(zhàn)
- 從0到1:HTML+CSS快速上手
- Django:Web Development with Python
- 新編Premiere Pro CC從入門到精通
- 從0到1:Python數(shù)據(jù)分析
- H5頁面設(shè)計(jì):Mugeda版(微課版)
- PHP編程基礎(chǔ)與實(shí)例教程
- Android群英傳
- Learning Nessus for Penetration Testing
- 玩轉(zhuǎn).NET Micro Framework移植:基于STM32F10x處理器
- Maven for Eclipse
- Mastering OAuth 2.0
- Google Maps JavaScript API Cookbook
- Spring Boot 3:入門與應(yīng)用實(shí)戰(zhàn)