Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

number before the positional format code. Python then positions the number accordingly within that
space area, as you can see here:


Click here to view code image


>>> print('The result is {0:>10d}'.format(test1))
The result is 45
>>>

Python reserves 10 spaces for the output of the numeric value and then right-aligns the value within
that space area.


With all these formatting options, you should be able to create custom reports with numeric data in no
time!


Summary


This hour explores how Python handles text strings, and what functions you have available for
working with them. You can use slicing to extract substrings out of a larger string at a specific
location, or you can use the string-splitting functions to extract substrings based on a separation
character. You can also use some search functions to search through a string to find a substring value.
Finally, some handy string formatting functions help you format any output strings that your Python
scripts produce.


In the next hour, we’ll explore how to use files with your Python scripts. It’s important to know how
to store and retrieve data from your scripts, and using plain files is the easiest way to do that!


Q&A


Q. Does Python support searching for text in strings using regular expressions?
A. Yes. Regular expressions are complicated enough to have their own hour (see Hour 16,
“Regular Expressions”).
Q. Can you embed nonprintable and other characters in Python string values?
A. Yes, you can use Unicode escape encoding to embed any Unicode character using its numeric
code. Just precede the code with a \u. For example, the Unicode code for a space is 0020, so
to embed it in a string you use, do this:

Click here to view code image





print('This\u0020is\u0020a\u0020test')
This is a test





Workshop


Quiz


1. What Python string function should you use to exchange a word in a string with another word?
a. swapcase()
b. split()
c. replace()
d. find()
Free download pdf