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

(singke) #1

Hour 10. Working with Strings


What You’ll Learn in This Hour:
How to create strings
Working with string functions
Formatting strings for output

One of the strong points of the Python programming language is its ability to work with text. Python
makes manipulating, searching, and formatting text data almost painless. This hour explores how to
create and work with text strings in your Python scripts.


The Basics of Using Strings


Before we dive too deeply into the Python text world, let’s take a look at the basics of working with
text. For starters, Python handles text data as a string data type. The following sections outline how to
use Python to create and work with string values and how to add text-handling features to your Python
scripts.


String Formats


Unfortunately, how Python handles string values has drastically changed in version 3. Previous
versions of Python stored strings in ASCII format, which uses a single byte value for each character.


Python v3 changed that, and Python now uses Unicode format to store strings. The Unicode format
uses 2 bytes to store each character, so it can accommodate a lot more text characters than the ASCII
format does. This enables it to support many different languages, making it more popular in the world
programming community.


By the Way: Using ASCII in Python v3
You can still work with ASCII characters and ASCII code values in Python v3. You
can store ASCII string characters as binary data by storing the raw ASCII code value
as a binary value, as in this example:
Click here to view code image
>>> binarystring = b'This is an ASCII string value'
>>> print(binarystring)
b'This is an ASCII string value'
>>> print(binarystring[1])
104
>>>
Because Python stores the string value as binary data, if you try to directly access an
individual letter, you’ll get the binary code for that letter. You can use the chr()
function to convert the ASCII code into the corresponding string value, like this:
Click here to view code image
>>> print(chr(binarystring[1]))
h
>>>
Free download pdf