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:

'hello'
"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.
Out[1]:
'hellothere'
In [2]:
greeting = 'hi'
In [3]:
greeting
Out[3]:
'hi'
In [4]:
greeting * 3  # Concatenate 3 copies of the string variable greeting refers to.
Out[4]:
'hihihi'
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.
Out[5]:
'hi'

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.'''
Out[6]:
'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.