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

(singke) #1

If you’re working with the English language in your scripts, the Python v3 change to Unicode format
isn’t readily apparent. You still store your text values the same way as in previous versions, and you
retrieve them the same way, too. However, with Unicode you now have access to a wider variety of
special characters that you can accommodate in your scripts!


Creating Strings


Creating string values in Python is pretty straightforward. You just use a simple assignment statement
to create a value and assign it to a variable. However, with string values, you must use quotes around
the data to delineate the start and end of the string value, as in this example:


Click here to view code image


>>> string1 = 'This is a test string'
>>> print(string1)
This is a test string
>>>

You can use either single or double quotes to delineate a string value, but it’s become somewhat
standard in the Python community to use single quotes, unless there are quotes inside the text value
itself.


If the text value includes single quotes, you can use double quotes to define the string beginning and
end:


Click here to view code image


>>> string2 = "This'll work when defining a string"
>>> print(string2)
This'll work when defining a string
>>>

Or you can escape the quotes by placing a backslash in front of the quotes in the string value:


Click here to view code image


>>> string3 = 'This\'ll also work when defining a string'
>>> print(string3)
This'll also work when defining a string
>>>

The backslash isn’t part of the string value; it just tells Python that the single quote in the data is part
of the value. The same technique also works for embedding double quotes inside the string value.


You can break up long string values onto separate lines in your program or in the IDLE interface by
adding a backslash at the end of the line and continuing the string on the next line. Python glues the
two lines together to create a single string value, as shown here:


Click here to view code image


>>> string4 = 'This is a long string value \
that spans multiple lines.'
>>> print(string4)
This is a long string value that spans multiple lines.
>>>

There’s another method for creating long string values, called triple quotes. With the triple quotes
method, you place three single or double quotes in a row to define the start of the string, and then you

Free download pdf