Introduction to Strings¶
A string object is a piece of text, or in other words, a sequence 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 the cell below, we define a string variable, with the value "Hello World!"
, and we then print the result.
my_string = "Hello world!"
print(my_string)
Hello world!
The official name of the Python string type is str
. We confirm this be calling type()
on my_string
.
type(my_string)
str
Empty Strings¶
It is possible to define a string that contains no characters. Such a string is referred to as an empty string. We can define an empty string by placing two single or double quotes next to each other without any characters between them. We see an example of this in the next cell.
empty_string = ""
print(empty_string)
We will see a practical use of empty strings later in this lesson.
The len()
Function¶
Python provides several built-in functions for working with strings. The first such function we will discuss is len()
. The len()
function allows you to determine the length of a string.
x = "There are 39 characters in this string."
print(len(x))
39
As you might expect, an empty string has a length of zero.
print(len(empty_string))
0