- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
2.7 Strings
Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pairs of single or double quotes. Triple quotes (three consecutive single or double quotes) can be used to escape special characters. Subsets of strings can be taken using the index ( [ ] ) and slice ( [ : ] ) operators, which work with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. The plus ( + ) sign is the string concatenation operator, and the asterisk ( * ) is the repetition operator. Here are some examples of strings and string usage:
>>> pystr = 'Python' >>> iscool = 'is cool!' >>> pystr[0] 'P' >>> pystr[2:5] 'tho' >>> iscool[:2] 'is' >>> iscool[3:] 'cool!' >>> iscool[-1] '!' >>> pystr + iscool 'Pythonis cool!' >>> pystr + ' ' + iscool 'Python is cool!' >>> pystr * 2 'PythonPython' >>> '-' * 20 '--------------------' >>> pystr = '''python ... is cool''' >>> pystr 'python\nis cool' >>> print pystr python is cool >>>
You can learn more about strings in Chapter 6.