Chapter 5. Text Strings
I always liked strange characters.
Tim Burton
Computer books often give the impression that programming is all about math. Actually, most programmers work with strings of text more often than numbers. Logical (and creative!) thinking is often more important than math skills.
Strings are our first example of a Python sequence.
In this case, they’re a sequence of characters.
But what’s a character?
It’s the smallest unit in a writing system,
and includes letters, digits, symbols, punctuation,
and even white space or directives like linefeeds.
A character is defined by its meaning (how it’s used),
not how it looks.
It can have more than one visual representation
(in different fonts),
and more than one character can have the same appearance
(such as the visual H
,
which means the H
sound in the Latin alphabet
but the Latin N
sound in Cyrillic).
This chapter concentrates on how to make and format simple
text strings,
using ASCII (basic character set) examples.
Two important text topics are deferred to Chapter 12:
Unicode characters
(like the H
and N
issue I just mentioned)
and
regular expressions (pattern matching).
Unlike other languages, strings in Python are immutable. You can’t change a string in place, but you can copy parts of strings to another string to get the same effect. We look at how to do this shortly.
Create with Quotes
You make a Python string by enclosing characters in matching single or double quotes:
>>>
'Snap'
'Snap'
>>>
"Crackle"
'Crackle' ...
Get Introducing Python, 2nd Edition 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.