FREE Courses
Text

Strings

Lesson 6

A string is simply a sequence of one or more characters—”a” is a string, “Hello There” is a string, if you were silly enough to load it all into a single variable, an entire book could be a string. String characters don’t have to be printable—a string can contain any Unicode character.

Strings are immutable. An immutable object cannot be changed after it’s created. I will be talking more about immutable and mutable objects shortly when I cover lists, tuples and dictionaries.

To create a string, you simply enclose the string in single or double quotes:

x = 'Hello' 
y = "There"

The only time it matters if you use single or double quotes is if there are quotes in the string:

a = 'This doesn't work'      # BAD, will break on
                             # quote in "doesn't" 
b = "Wasn't that easy"       # GOOD
c = '"Air quotes" are silly' # Also GOOD

If there are multiple quotes in the string, you must escape the quotes with a backslash (\):

d = "Aren't quotes \"fun\"?"

Strings are a special class built in to Python, with many class methods available for working with them. Here are a few examples using the Python interactive interpreter:

>>> "hello".capitalize()    # Manipulate a string directly
'Hello'                     # Capitalize string
>>> "hello".upper()         # Uppercase string 'HELLO'
>>> greet = "Hello There"   # Work with string variable
>>> greet[0]                # String indexing
'H'                         # First character
>>> greet[6]
'T'                         # Seventh character
>>> greet[:4]               # String slicing
'Hell'                      # First four characters
>>> greet[len(greet)-4:]
'here'                      # Last four characters
>>> greet[::-1]             # Reverse a string 'erehT olleH'
>>> padded = "    My name is Nige    "
>>> padded.lstrip()

'My name is Nige    '         # Removing whitespace
>>> padded.rstrip()
'    My name is Nige'
>>> greet.replace("e","_")    # Replacing characters
                              # in a string
'H_llo Th_r_'
>>> greet.split()             # Splitting strings
['Hello', 'There']            # Default split is space
>>> greet.split("e")          # But can split on
                              # anything
['H', 'llo Th', 'r', '']
>>>

Here’s a screenshot of the exercise:

Like math and numbers, this is only a small taste of what can be achieved with the string class. For more information see the Python string class documentation.

Formatting Strings

Another useful thing you can do with strings is to use string interpolation to substitute values into a formatted string. This is easier explained with an example. Try this at the Python prompt:

>>> "There are %s apples left" % "four"

String interpolation is performed with the modulo (%) operator and takes the form:

format % values

So, when you enter the above code, Python replaces the string placeholder (%s) with the string “four”. When you hit enter, Python prints out:

'There are four apples left'
>>>

This works on multiple substitutions, however, with multiple substitutions the values must be passed in as a tuple (more on tuples shortly):

>>> "There are %s apples and %s oranges left" % ("four","two")
'There are four apples and two oranges left'

String formatting will substitute numbers as well. For example, %i will insert an integer:

>>> "There are %i apples and %i oranges left" % (2,7)
'There are 2 apples and 7 oranges left'
>>>

Other format strings include:

  • %f. A floating point decimal
  • %X. A signed hexadecimal (uppercase)
  • %c. A single character

Here’s a screenshot of the exercise:

For more on formatting strings, see the Python documentation on String Formatting Operations.

Lesson Resources

Pen