Книга: Practical Programming, Fourth Edition
Назад: Chapter 4: Working with Text
Дальше: Using Special Characters in Strings

Creating Strings of Characters

Computers may have been invented to do arithmetic, but these days, most of them spend a lot of their time processing text. Many programs create, store, search, and move text from one place to another.

Python uses type str to represent text as sequences of
characters

In Python, text is represented as a string, which is a sequence of characters (letters, digits, and symbols). The type whose values are sequences of characters is str. The characters consist of those from the Latin alphabet found on most North American keyboards, as well as Chinese morphograms, chemical and musical symbols, and other types of characters.

Strings are created by placing pairs of quotes around the text

In Python, you indicate that a value is a string by enclosing it in either single or double quotes. As you will see in , single and double quotes are equivalent, except for strings that contain quotes. Use whichever you prefer. (For docstrings, the Python style guidelines say that double quotes are preferred.) Here are two examples:

 >>>​​ ​​'Aristotle'
 'Aristotle'
 >>>​​ ​​"Isaac Newton"
 'Isaac Newton'

Note how Python always displays a string in single quotes, regardless of what quotes you used in the first place (unless the string contains a single quote and does not contain a double quote).

The opening and closing quotes must match:

 >>>​​ '​​Charles​​ ​​Darwin​​"
  File "​​<python-input-0>​​", line 1
  'Charles Darwin"
  ^
 SyntaxError: unterminated string literal (detected at line 1)

Python attempts to find the matching closing single quote but fails, resulting in an unterminated string.

Strings can contain any number of characters, limited only by computer memory. The shortest string is the empty string, containing no characters at all:

 >>>​​ ​​''
 ''
 >>>​​ ​​""
 ''

Operations on Strings

Python has a built-in function, len, that returns the number of characters between the opening and closing quotes:

 >>>​​ ​​len(​​'Albert Einstein'​​)
 15
 >>>​​ ​​len(​​'123!'​​)
 4
 >>>​​ ​​len(​​' '​​)
 1
 >>>​​ ​​len(​​''​​)
 0

You can concatenate (“glue up”) two strings using the + operator, which produces a new string containing the characters from both operands:

 >>>​​ ​​'Albert'​​ ​​+​​ ​​' Einstein'
 'Albert Einstein'

When + has two string operands, it is referred to as the concatenation operator. The + operator is one of the most frequently overloaded operators in Python. So far, you’ve applied it to integers, floating-point numbers, and strings, and you’ll apply it to several more types in later chapters.

As the following example shows, adding an empty string to another string produces a new string that is just like the nonempty operand:

 >>>​​ ​​"Alan Turing"​​ ​​+​​ ​​''
 'Alan Turing'
 >>>​​ ​​""​​ ​​+​​ ​​'Grace Hopper'
 'Grace Hopper'

Here is an interesting question: Can operator + be applied to a string and a numeric value? If so, would addition or concatenation occur? Let’s give it a try:

 >>>​​ ​​'NH'​​ ​​+​​ ​​3
 Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
  'NH' + 3
  ~~~~~^~~
 TypeError: can only concatenate str (not "int") to str

This is the second time that you’ve seen a type error. The first time, in , you didn’t pass the correct number of parameters to a function. Here, Python didn’t like you combining values of different data types. Because the first operand was a string, Python expected the second operand also to be a string, but instead it was an integer. Now consider this example:

 >>>​​ ​​9​​ ​​+​​ ​​' planets'
 Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
  9 + ' planets'
  ~~^~~~~~~~~~~~
 TypeError: unsupported operand type(s) for +: 'int' and 'str'

Here, because Python saw a 9 first, it expected the second operand also to be numeric. The order of the operands affects the error message that is displayed.

The concatenation operator must be applied to two strings. If you want to join a string with a number, apply the function str to the number to get its string representation, and then apply the concatenation:

 >>>​​ ​​'Four score and '​​ ​​+​​ ​​str(7)​​ ​​+​​ ​​' years ago'
 'Four score and 7 years ago'

Function int can be applied to a string whose contents look like an integer, and float can be applied to a string whose contents are numeric:

 >>>​​ ​​int(​​'0'​​)
 0
 >>>​​ ​​int(​​"11"​​)
 11
 >>>​​ ​​int(​​'-324'​​)
 -324
 >>>​​ ​​float(​​'-324'​​)
 -324.0
 >>>​​ ​​float(​​"56.34"​​)
 56.34

It isn’t always possible to get an integer or a floating-point representation of a string, and when an attempt to do so fails, an error occurs:

 >>>​​ ​​int(​​'a'​​)
 Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
  int('a')
  ~~~^^^^^
 ValueError: invalid literal for int() with base 10: 'a'
 >>>​​ ​​float(​​'b'​​)
 Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
  float('b')
  ~~~~~^^^^^
 ValueError: could not convert string to float: 'b'

In addition to +, len, int, and float, operator * can be applied to strings. A string can be repeated using the operator * and an integer, like this:

 >>>​​ ​​'AT'​​ ​​*​​ ​​5
 'ATATATATAT'
 >>>​​ ​​4​​ ​​*​​ ​​'-'
 '----'

If the integer is less than or equal to zero, the operator yields an empty string:

 >>>​​ ​​'GC'​​ ​​*​​ ​​0
 ''
 >>>​​ ​​'TATATATA'​​ ​​*​​ ​​-3
 ''

Strings are values; you can assign a string to a variable. Also, operations on strings can be applied to those variables:

 >>>​​ ​​sequence​​ ​​=​​ ​​'ATTGTCCCCC'
 >>>​​ ​​len(sequence)
 10
 >>>​​ ​​new_sequence​​ ​​=​​ ​​sequence​​ ​​+​​ ​​'GGCCTCCTGC'
 >>>​​ ​​new_sequence
 'ATTGTCCCCCGGCCTCCTGC'
 >>>​​ ​​new_sequence​​ ​​*​​ ​​2
 'ATTGTCCCCCGGCCTCCTGCATTGTCCCCCGGCCTCCTGC'
Назад: Chapter 4: Working with Text
Дальше: Using Special Characters in Strings