Linux/Unix > Python Essential Reference, Second Edition > 1. A Tutorial Introduction > Strings | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137110162165011202136172174

### Strings

To create string literals, enclose them in single, double, or triple quotes as follows:

    a = 'Hello World'
    b = "Python is groovy"
    c = """What is footnote 5?"""

The same type of quote used to start a string must be used to terminate it. Triple-quoted strings capture all the text that appears prior to the terminating triple quote, as opposed to single- and double-quoted strings, which must be specified on one logical line. Triple quotes can be done with either single quotes (as in the following example) or double quotes (as in the above example). Triple-quoted strings are useful when the contents of a string literal span multiple lines of text such as the following:

    print '''Content-type: text/html

    <h1> Hello World </h1>
    Click <a href="http://www.python.org">here</a>.
    '''

Strings are sequences of characters indexed by integers starting at zero. To extract a single character, use the indexing operator `s` `[``i` `]` like this:

    a = "Hello World"
    b = a[4]                # b = 'o'

To extract a substring, use the slicing operator `s` `[``i` `:``j` `]`. This extracts all elements from s whose index `k` is in the range `i <= k < j` . If either index is omitted, the beginning or end of the string is assumed, respectively:

    c = a[0:5]              # c = "Hello"
    d = a[6:]               # d = "World"
    e = a[3:8]              # e = "lo Wo"

Strings are concatenated with the plus (`+`) operator:

    g = a + " This is a test"

Other datatypes can be converted into a string by using either the `str()` or `repr()` function or backquotes (```), which are a shortcut notation for `repr()`. For example:

    s = "The value of x is " + str(x)
    s = "The value of y is " + repr(y)
    s = "The value of y is " + `y`

In many cases, `str()` and `repr()` return identical results. However, there are subtle differences in semantics that are described in later chapters.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.