This lesson will be a double-shot of essential Python types: strings and dictionaries.

Strings

One place where the Python language really shines is in the manipulation of strings. This section will cover some of Python's built-in string methods and formatting operations.

Such string manipulation patterns come up often in the context of data science work, and is one big perk of Python in this context.

String syntax

You've already seen plenty of strings in examples during the previous lessons, but just to recap, strings in Python can be defined using either single or double quotations. They are functionally equivalent.

Double quotes are convenient if your string contains a single quote character (e.g. representing an apostrophe).

Similarly, it's easy to create a string that contains double-quotes if you wrap it in single quotes:

If we try to put a single quote character inside a single-quoted string, Python gets confused:

We can fix this by "escaping" the single quote with a backslash.

The table below summarizes some important uses of the backslash character.

What you type... What you get example print(example)
\' ' 'What\'s up?' What's up?
\" " "That's \"cool\"" That's "cool"
\\ \ "Look, a mountain: /\\" Look, a mountain: /\
\n
"1\n2 3" 1
2 3

The last sequence, \n, represents the newline character. It causes Python to start a new line.

In addition, Python's triple quote syntax for strings lets us include newlines literally (i.e. by just hitting 'Enter' on our keyboard, rather than using the special '\n' sequence). We've already seen this in the docstrings we use to document our functions, but we can use them anywhere we want to define a string.

The print() function automatically adds a newline character unless we specify a value for the keyword argument end other than the default value of '\n':

Strings are sequences

Strings can be thought of as sequences of characters. Almost everything we've seen that we can do to a list, we can also do to a string.

But a major way in which they differ from lists is that they are immutable. We can't modify them.

String methods

Like list, the type str has lots of very useful methods. I'll show just a few examples here.

Going between strings and lists: .split() and .join()

str.split() turns a string into a list of smaller strings, breaking on whitespace by default. This is super useful for taking you from one big string to a list of words.

Occasionally you'll want to split on something other than whitespace:

str.join() takes us in the other direction, sewing a list of strings up into one long string, using the string it was called on as a separator.

Building strings with .format()

Python lets us concatenate strings with the + operator.

If we want to throw in any non-string objects, we have to be careful to call str() on them first

This is getting hard to read and annoying to type. str.format() to the rescue.

So much cleaner! We call .format() on a "format string", where the Python values we want to insert are represented with {} placeholders.

Notice how we didn't even have to call str() to convert position from an int. format() takes care of that for us.

If that was all that format() did, it would still be incredibly useful. But as it turns out, it can do a lot more. Here's just a taste:

You could probably write a short book just on str.format, so I'll stop here, and point you to pyformat.info and the official docs for further reading.

Dictionaries

Dictionaries are a built-in Python data structure for mapping keys to values.

In this case 'one', 'two', and 'three' are the keys, and 1, 2 and 3 are their corresponding values.

Values are accessed via square bracket syntax similar to indexing into lists and strings.

We can use the same syntax to add another key, value pair

Or to change the value associated with an existing key

Python has dictionary comprehensions with a syntax similar to the list comprehensions we saw in the previous tutorial.

The in operator tells us whether something is a key in the dictionary

A for loop over a dictionary will loop over its keys

We can access a collection of all the keys or all the values with dict.keys() and dict.values(), respectively.

The very useful dict.items() method lets us iterate over the keys and values of a dictionary simultaneously. (In Python jargon, an item refers to a key, value pair)

To read a full inventory of dictionaries' methods, click the "output" button below to read the full help page, or check out the official online documentation.

Your Turn

You've learned a lot of Python... go test your skills with some realistic programming applications.


Have questions or comments? Visit the Learn Discussion forum to chat with other Learners.