Section 2.7. Strings


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.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net