4.3. String Handling

There are only a few applications which do not handle textual data at all. In some cases you are not interested in text as such, but you need to convert textual input to a format which is easy to handle programmatically, for instance to lists or integers. Finally, when your application has processed the data, it is often printed out in textual form, so the application must convert internal data structures back to text.

Luckily, all this is straightforward in Python. In this section we introduce basic operations on strings, which are used by many examples in this book. Section 4.4, which introduces you to the SMS inbox, requires some power tools for string handling.

In Python, strings are objects too. In effect, this means that all string-related functions are available automatically without any imports, but you need to remember to use the dot notation, for example txt.find ("is"), when calling the string functions. Note that it is not possible to modify a string after creation. All string operations return a new string and leave the original string intact.

4.3.1. Defining a String

There are many ways to define new strings:

txt = "Episode XXXIV"
txt = 'Bart said: "Eat my shorts"'
txt = """Homer's face turned red. He replied: "Why you little!""""

The first line uses double quotes to enclose a string. This is the most usual way to define a string. The second line uses single quotes. It comes in handy if your string contains double quotes. The last line shows ...

Get Mobile Python: Rapid Prototyping of Applications on the Mobile Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.