Introduction to Strings

Until now, we've only been working with numberic values and two numeric types (int and float). Next, we will work with a strings.

Strings are sequences of characters and in Python this is type str.

Strings in Python start and end with a single quotes (') or double quotes ("). A string can be made up of letters, numbers, and special characters. For example:

"how are you?"
'first- and second- year'

Like other types, we can assign use them in expressions and in variable assignment statements:

In [1]:
'hello' + 'there'  # This is string concatentation.
In [2]:
greeting = 'hi'
In [3]:
In [4]:
greeting * 3  # Concatenate 3 copies of the string variable greeting refers to.
In [5]:
greeting  # Notice that the value that greeting refers to is unchanged.  
          # To produce a new string, we used the string that greeting refers to.

Multi-line strings

In addition to single- and double-quotes, we can also use triple-quotes to represent strings. A triple-quoted string can span multiple lines:

In [6]:
'''This is
a longer string
that spans
multiple lines.'''
'This is\na longer string\nthat spans\nmultiple lines.'

Notice that when the triple-quoted string is evaluated, it produces a single-quoted string containing \n. The newline character, \n, means "switch to a new line."

You'll learn more about strings at upcoming sessions.