The course is part of this learning path
This course explores Strings in Python and is part of a series of content designed to help you learn to program with the Python programming language.
Learning Objectives
- Describe the different ways to define a string in code
- Describe the purpose of the escape character
- Describe three different ways to format a string
Intended Audience
This course was designed for first-time developers wanting to learn Python.
Prerequisites
This is an introductory course and doesn’t require any prior programming knowledge.
Hello, and welcome! My name is Ben Lambert, and I’ll be your instructor for this course. This course is part of a series of content designed to help you learn to program with the Python programming language.
Should you wish to ask me a specific question, you can do that with the contact details on screen. You can also reach support by using the email address: support@cloudacademy.com. And one of our cloud experts will reply.
The Python runtime includes many different types of objects; used for a variety of purposes. Integers, lists, booleans, callables. They all serve some purpose. The purpose of Python’s string object is to represent a sequence of characters.
In this lesson, we’re going to explore strings a bit more in-depth. Working with text is so common that Python’s language syntax includes mechanisms for us to create strings. Python provides multiple ways to define a string in code. Strings can be enclosed in either single or double quotes. They can also be defined using three opening and three closing single-or-double quotes.
Why would you use one over another? Let’s talk about this a bit more. Let’s break this into two groups, single-line strings and multi-line strings.
To define single line strings we can use either a set of single quotes or a set of double quotes. As long as the opening and closing quotes match, you can use either. So, if they’re the same, why have multiple ways to define strings?
Having different options allows us to select which one to use based on the content of the string. For example: imagine that you bind a name to the string: “you’re”. As in the contraction of: you are.
Notice that this text includes a single quote. When the Python interpreter reads this line it sees the opening quote and then assumes the next single quote is the end of the string. So when it sees the rest of this text here, it raises an exception because this isn’t valid Python code.
We have options for fixing this. First, Python provides what it calls an escape character. By placing a backslash before the single quote in the text we instruct the interpreter to treat this as part of the text. While using the escape character works just fine, we can also use the other quote style. The value in this is that it’s clearer to read because it doesn’t need an escape character.
These two styles of string are both intended to enclose single lines of text. If the text we enter in these strings resides on a single line then either type will work.
If we were to enter a new line causing the closing quote to fall onto a new line, the interpreter is going to raise an exception. To define multi-line strings in code we can use triple quotes. The interpreter allows us to use a pair of either three single or double quotes.
This style of string is useful for multiple lines, as well including single and double quotes without requiring the escape character. When working with strings they often are used as templates. Where we dynamically fill in some information.
Imagine that we want to print a greeting to the console. Something simple that just says hello followed by the person’s name. Python provides us with multiple mechanisms to format strings in many different ways.
Let’s talk about three options. We’ll cover the original syntax; the format method; and the new syntax. Python’s original syntax for formatting strings is based on the way the C programming language formatted strings. This syntax involves using placeholders which serve as a stand-in for some actual value. There are several placeholders which are used to represent different types of objects.
We can specify multiple placeholders and then populate them using the format operator followed by a tuple containing the positional arguments. The order of the arguments provided on the right need to align with the placeholders.
This method is usable though, there are other ways to format a string which offer more formatting options. The format method of a string is another way to format a string’s text. The format method has its own syntax for defining placeholders and even defining rules about how to format the provided data. The format method’s syntax uses curly brackets as placeholders.
By using empty brackets we can create a placeholder that will be filled in by the argument provided to the format method in the same relative position. This syntax is useful though, it has its limitations. For example, if we wanted to repeat the cat’s name, we would have to add another set of brackets and repeat the name in the format method’s arguments.
To avoid having to repeat any of the arguments, we can use the index of the arguments to indicate which argument we want to replace with. Notice that indexes begin at zero in Python. So index zero references the name Ada. Index one references the number 3.
We can also add further clarity to the code by using keyword arguments. We’ll cover keyword arguments in future content. For now, just know that by using a name between brackets we can specify format details by name. And those match up to the name specified in the format method.
The format method includes its own mini-syntax for formatting strings. It can perform actions such as centering text; setting a number’s thousands separator; among other string formatting tasks. We’re not going to dive into this rabbit hole. At this point knowing it exists is more valuable than trying to force you to learn it all.
The newest mechanism for formatting strings is called f-strings. This tends to be my preferred option because it allows us to place a Python expression inside of curly brackets. In this simple example we have the names cat and age bound to a string and integer.
Then we have an f-string. Notice this letter f is placed just before the opening quote. This instructs the interpreter to treat this as an f-string. Which means it will look for brackets and convert the expression into a string.
Just as the other two formatting options include their own syntax, so do f-strings. F-strings are rather flexible. Inside the brackets we can run valid Python expressions. For example we could add one to the age. We could also call functions. Imagine that we had a function used to return a person’s name. We could call that function and have its return value displayed in the text.
All of these options are viable mechanisms to format strings. I tend to use f-strings and the format method because they’re more expressive. However, there’s no wrong answer. Use whichever one makes your code easiest to read. Okay, this seems like a natural stopping point. Here are your key takeaways for this lesson:
-
We can create single-line strings in code using a pair of single or double quotes.
-
We can create multi-line strings using a pair of either three single or double quotes.
-
The purpose of the backslash escape character is to instruct the interpreter to consider the next character as part of the string.
-
Three different ways to format strings are:
-
The original C-style syntax which uses the percent sign.
-
The string’s format method which has its own syntax.
-
The new option which is called f-strings which has its own syntax.
That's all for this lesson. Thanks so much for watching. And I’ll see you in another lesson!
Ben Lambert is a software engineer and was previously the lead author for DevOps and Microsoft Azure training content at Cloud Academy. His courses and learning paths covered Cloud Ecosystem technologies such as DC/OS, configuration management tools, and containers. As a software engineer, Ben’s experience includes building highly available web and mobile apps. When he’s not building software, he’s hiking, camping, or creating video games.