Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:
>>> 'spam eggs' 'spam eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> "\"Yes,\" he said." '"Yes," he said.' >>> '"Isn\'t," she said.' '"Isn\'t," she said.'
hello = "This is a rather long string containing\n\ several lines of text just as you would do in C.\n\ Note that whitespace at the beginning of the line is\ significant.\n" print hello
which would print the following:
This is a rather long string containing several lines of text just as you would do in C. Note that whitespace at the beginning of the line is significant.
Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string.
print """ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """
produces the following output:
Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to
Strings can be concatenated (glued together) with the + operator, and repeated with *:
>>> word = 'Help' + 'A' >>> word 'HelpA' >>> '<' + word*5 + '>' '<HelpAHelpAHelpAHelpAHelpA>'
Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.
>>> word[4] 'A' >>> word[0:2] 'He' >>> word[2:4] 'lp'
>>> word[:2] # The first two characters 'He' >>> word[2:] # All but the first two characters 'lpA'
>>> word[:2] + word[2:] 'HelpA' >>> word[:3] + word[3:] 'HelpA'
>>> word[1:100] 'elpA' >>> word[10:] '' >>> word[2:1] ''
>>> word[-1] # The last character 'A' >>> word[-2] # The last-but-one character 'p' >>> word[-2:] # The last two characters 'pA' >>> word[:-2] # All but the last two characters 'Hel'
>>> word[-0] # (since -0 equals 0) 'H'
>>> word[-100:] 'HelpA' >>> word[-10] # error Traceback (innermost last): File "<stdin>", line 1 IndexError: string index out of range
+---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1
For nonnegative indices, the length of a slice is the difference of the indices, if both are within bounds, e.g., the length of word[1:3] is 2.
The built-in function len() returns the length of a string:
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
guido@python.org