String ¶
The next frequently used data type in Python is called the
string
, which handles data in the form of text like
"Hello"
and
"Python is awesome!"
.
print(type("Hello"))
print(type("Python is awesome!"))
<class 'str'> <class 'str'>
But, why do they call it a
string
?
This terminology is borrowed from linguistics where a
string
of characters represents a sequence of symbols.
In all programming languages, we use this term to mean a "sequence of characters" that do not even have to be letters of any language.
print(type("👀◀↿♥🚀"))
<class 'str'>
Anything that I put in between a pair of
"
becomes a
string
, even if it is a number.
Again, the presence of a
"
is an instruction to Python to store that as a
string
.
print(type("3.1415926"))
<class 'str'>
Note that you can also use single quotes.
print(type('Hello'))
<class 'str'>
It does not matter which one you use, as long as you match them.
For example, the following code would throw a
SyntaxError
.
print("Hello')
Should you use
"
or
'
?
Well, I usually recommend using
"
because sentences have a higher chance of using
'
in the actual string.
For example the following code is fine.
print("Tessa's favorite toy is a teddy bear.")
Tessa's favorite toy is a teddy bear.
However, if I used
'
to define the
string
I would get an error because I closed the string after
'Tessa'
.
print('Tessa's favorite toy is a teddy bear.')
Also, note that you can do some "arithmetic-like operations" with
string
.
You can use your own intuition on what would be possible.
For example, I can tell Python to repeat a string a specific number of times with an
int
.
print("Hello" * 3)
HelloHelloHello
But I cannot repeat a string
3.2
times.
I can tell Python to add (i.e., combine) two strings.
print("Hello" + "Hello")
HelloHello
But something like division would not make sense.