2. Basic Types: Strings
Strings
In addition to numbers, Python also supports textual data. The typing that includes all forms of text is the #\color{#4271ae}{\mathtt{\text{str}}}# typing, which is short for string.
String definitionIn computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. In most programming languages, a string is contained by quotes.
A string can be of any length; a string can be just a word, a sentence, or an entire body of text.
Creating a stringThe most common way to declare a #\color{#4271ae}{\mathtt{\text{str}}}# is by using either single or double quotes. Internally, there's no difference; it results in exactly the same string:
|
>>> "Hello, world!"
|
|
'Hello, world!'
|
|
>>> 'Hello, world!'
|
|
'Hello, world!'
|
When containing a string in one type of quotes, we can use the other type of quotes within the string:
|
>>> '"Hello, world!" they said.'
|
|
'"Hello, world!" they said.'
|
Note that, when swapping quotes in such a string, this won't result in the same string:
|
>>> "'Hello, world!' they said."
|
|
"'Hello, world!' they said."
|
Unlock full access
Teacher access
Request a demo account. We will help you get started with our digital learning environment.