Lesson 02 - Strings

The following topics are discussed in this notebook:

  • An introduction to the string data type.
  • Escape characters.
  • Operations on strings.
  • String functions.

Additional Resources

Introduction to Strings

A string object is a piece of text, or in otherwords, a collection of characters. When defining a string, we must put the characters that compose it inside either single or double quotes. These quotes are what allows Python to distinguish between a string and a command.

In [1]:
my_string = "Hello world!"
print(my_string)
Hello world!
In [2]:
type(my_string)
Out[2]:
str

The print() function is able to take several strings as arguments.

In [3]:
a = "foo"
b = "bar"
print(a, b)
foo bar

Escape Sequences

An escape sequence is a sequence of characters that Python applies special meaning to when it encounters them in a string. Several common escape sequences are listed below.

Escape Character Result
\' Prints a single quote.
\" Prints a double quote.
\n Inserts a new line.
\t Inserts a tab.
In [4]:
quote = "\"Python is awesome\", he said."
print(quote)
"Python is awesome", he said.
In [5]:
tale2cities = "It was the best of times.\nIt was the worst of times."
print(tale2cities)
It was the best of times.
It was the worst of times.
In [6]:
print("Regular.")
print("\tIndented.")
print("\t\tDouble indented.")
Regular.
	Indented.
		Double indented.

Operations involving strings

When the + symbol is used between strings, it combines, or concatenates the strings.

In [7]:
a = "star"
b = "wars"
c = a + b
print(c)
starwars
In [8]:
d = a + " " + b
print(d)
star wars

If we try to combine a string and a number with +, we will get an error.

In [9]:
print("one" + 2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-e8bf6f236ab3> in <module>()
----> 1 print("one" + 2)

TypeError: must be str, not int

Note that numbers enclosed with quotes are also considered strings. Python does not recongnize them as numbers.

In [10]:
print("1" + 2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-2c8b8ec3d2f2> in <module>()
----> 1 print("1" + 2)

TypeError: must be str, not int

Although we are not able to "add" strings to numbers, we are able to "multiply" a string by a number.

In [11]:
print("blah " * 5)
blah blah blah blah blah 

Since the product of a string and an integer produces another string, expressions of this type can be concatenated together.

In [12]:
print("la " * 4 + "doo " * 3)
la la la la doo doo doo 

Python does NOT know how to "multiply" two strings.

In [13]:
a = "foo"
b = "bar"
print(a*b)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-7e707a899c71> in <module>()
      1 a = "foo"
      2 b = "bar"
----> 3 print(a*b)

TypeError: can't multiply sequence by non-int of type 'str'

String Functions

Python has several built-in functions for working with strings.

The len() function allows you to determine the length of a string.

In [14]:
x = "There are 39 characters in this string."
print(len(x))
39

Methods

The majority of the functions we will encounter when working with strings are methods. The difference between a method and other types of functions we will encounter is subtle, and is not something we are yet ready to fully dive into. For now, we simply note the following two points regarding methods:

  1. To use a method on a string, type the name of the string, followed by a dot, followed by the name of the method.
  2. The string itself is always passed to the method as the first argument.
In [15]:
myString = "There's a method in the madness."
print(myString.upper())
print(myString.lower())
print(myString.title())
THERE'S A METHOD IN THE MADNESS.
there's a method in the madness.
There'S A Method In The Madness.
In [16]:
print( myString.count("m") )
print( myString.count("e") )
2
5
In [17]:
a = "a "
b =  "no "
print( myString.replace(a, b) )
There's no method in the madness.

Converting numbers to strings

We will often wish to print statements that involve both strings and numeric variables. To accomplish this, we can convert the numeric objects to strings using the str() function.

In [18]:
x = 129
x2 = x**2
my_string = "The square of " + x + " is " + x2 + "."
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-a263bb7cd14a> in <module>()
      1 x = 129
      2 x2 = x**2
----> 3 my_string = "The square of " + x + " is " + x2 + "."

TypeError: must be str, not int
In [19]:
my_string = "The square of " + str(x) + " is " + str(x2) + "."
print(my_string)
The square of 129 is 16641.