Datatypes - Strings
We've already seen strings in previous examples, we will define it now.
Strings are a sequence of alpha-numeric characters.
A string can be empty, or contain any amount of letters or numbers. The term character is used to express something that is either a letter or number, and is part of the terminology that is common in the programming space. For example if we write just "h" then this is a character. If we write "hi" then this is a string, composed of the two characters "h" and "i".
Strings can be enclosed by either single or double quotes, just don't try mixing them!
Combining Strings
One of the nice features Python naturally provides for strings is the
capability to combine them together - a process usually referred
to as concatenation. We can concatenate multiple strings
together using just the plus sign +
.
When combining strings, spaces won't magically appear, it's up to the developer to make sure the combined string makes sense.
Casting from String to Int
We learned how to convert between int
and floats
by casting them in the
Datatypes - Integers and Floats lesson.
Since this is such a useful thing to be able to do. Let's learn how we
can do the same kind of thing with strings.
It is worth mentioning int
can only convert strings that
are ints to ints. If we try any of the following, we will receive an
error.
int("5.1")
int("5a")
ValueError: invalid literal for int() with base 10
Like many other types, there's much more to strings, such as searching for a substrings, changing the case, and other ways to manipulate them, which we will leave for the intermediate level of this path. For now, lets move on to lists.