Home > Articles > Open Source > Python

  • Print
  • + Share This
Like this article? We recommend

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-quoted strings can use either double quotes (as in the preceding example) or single quotes (as in the following example). Triple quoting is 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 some subtle differences in semantics. For details, see Chapter 5, "Control Flow," in Python Essential Reference, Second Edition (New Riders, 2001, ISBN 0-7357-1091-0).

  • + Share This
  • 🔖 Save To Your Account