PySchools Python Quick Reference Guide

Strings

«  Lists   ::   Contents   ::   Dictionaries  »

Strings

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
'helloworld'
>>> 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)
'h'
>>> a[-1]               # get get last character
'o'
>>> a[0:2]              # slicing works on string as well
'he'
>>> len(a)              # get number of characters in the string
5
>>> a.count('l')        # get the number of occurence of a particular character
2

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
'aello'

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()
'Hello'
>>> a.upper()
'HELLO'
>>> a.lower()
'hello'
>>> a.replace("e", "a")
'hallo'

Useful Methods for Finding Substrings

>>> a = "Hello World"
>>> a.startswith("H")
True
>>> a.endswith("D")
False
>>> a.find("World")
6
>>> a.index("World")
6
>>> a.find("world") # 'find' returns -1 if no substring is found.
-1
>>> 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  »