Chapter 5. Strings

The next major built-in type is the Python string an ordered collection of characters, used to store and represent text-based information. From a functional perspective, strings can be used to represent just about anything that can be encoded as text: symbols and words (e.g., your name), contents of text files loaded into memory, Internet addresses, Python programs, and so on.

You may have used strings in other languages too; Python's strings serve the same role as character arrays in languages such as C, but Python's strings are a somewhat higher level tool than arrays. Unlike C, Python strings come with a powerful set of processing tools. Also unlike languages like C, Python has no special type for single characters (like C's char), only one-character strings.

Strictly speaking, Python strings are categorized as immutable sequences meaning that they have a left-to-right positional order (sequence), and cannot be changed in place (immutable). In fact, strings are the first representative of the larger class of objects called sequences. Pay special attention to the operations introduced here, because they will work the same on other sequence types we'll see later, such as lists and tuples.

Table 5-1 introduces common string literals and operations. Empty strings are written as two quotes with nothing in between, and there are a variety of ways to code strings. For processing, strings support expression operations such as concatenation (combining strings), slicing (extracting sections), indexing (fetching by offset), and so on. Besides expressions, Python also provides a set of string methods that implement common string-specific tasks, as well as a string module that mirrors most string methods.

Table 5-1. Common string literals and operations

Operation

Interpretation

s1 = ''

Empty string

s2 = "spam's"

Double quotes

block = """..."""

Triple-quoted blocks

s3 = r'\temp\spam'

Raw strings

s4 = u'spam'

Unicode Strings

s1 + s2s2 * 3

Concatenate, repeat

s2[i] s2[i:j] len(s2)

Index, slice, length

"a %s parrot" % 'dead'

String formatting

S2.find('pa') s2.replace('pa', 'xx')s1.split( )

String method calls

for x in s2'm' in s2

Iteration, membership

Methods and modules are discussed later in this section. Beyond the core set of string tools, Python also supports more advanced pattern-based string processing with the standard library's re (regular expression) module, introduced in Chapter 27. This section starts with an overview of string literal forms and basic string expressions, and then looks at more advanced tools such as string methods and formatting.



Learning Python
Learning Python: Powerful Object-Oriented Programming
ISBN: 0596158068
EAN: 2147483647
Year: 2003
Pages: 253
Authors: Mark Lutz

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net