PySchools Python Quick Reference Guide


«  Lists   ::   Contents   ::   Dictionaries  »


String is one of the most common used data type in Python. You create a string by enclosing some characters or numbers in single (‘) or double (”) quotes.

>>> a = "hello"             # using double quote
>>> b = 'world'             # using single quote
>>> a + b                   # concatenates string
>>> type(a)                 # query for data type
<type 'str'>

>>> c = "How're you doing?" # mixing single and double quotes
>>> c
"How're you doing?"

>>> d = """ A long string
... that spans a few
... lines can be enclosed in
... triple quotes.
... """
>>> d
' A long string \nthat spans a few\nlines can be enclosed in \ntriple quotes.\n'

Accessing Values in a String

A string comprises of a sequence of characters, and quite a few methods/functions that work on list is applicable to String as well.

>>> a = "hello"
>>> a[0]                # get first character (same as list, zero indexed)
>>> a[-1]               # get get last character
>>> a[0:2]              # slicing works on string as well
>>> len(a)              # get number of characters in the string
>>> a.count('l')        # get the number of occurence of a particular character

Modifying a String

String is immutable, and therefore its value cannot be modified directly. However, you can “modify” a string by re-assigning the value to another string.

>>> a = "hello"
>>> a[0] = 'a'          # Not allow, produce error
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> b = 'a' + a[1:]     # replace the first character with 'a', and reassign the result to a new string
>>> b

Built-in String Methods

Python provides quite a few very handy string methods. Some commonly used ones are shown below. For a complete list, refer to Python Docs: String Methods.

>>> a = "hello"
>>> a.capitalize()
>>> a.upper()
>>> a.lower()
>>> a.replace("e", "a")

Useful Methods for Finding Substrings

>>> a = "Hello World"
>>> a.startswith("H")
>>> a.endswith("D")
>>> a.find("World")
>>> a.index("World")
>>> a.find("world") # 'find' returns -1 if no substring is found.
>>> a.index("world") # 'index' returns a error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

See also

Ready for some practice? Test your understanding at PySchools: Strings.

«  Lists   ::   Contents   ::   Dictionaries  »