Strings
Much of the world's data is text, and a piece of text represented in a computer is called a string. A string can represent a word, a sentence, or even the contents of every book in a library. Since text can include numbers (like this: 5) or truth values (True), a string can also describe those things.
Strings are enclosed in quotes. Like other values, they can be assigned names, and they have a type: str
.
tale_of_two_cities_opening = "It was the best of times, it was the worst of times, ..."
tale_of_two_cities_opening
type(tale_of_two_cities_opening)
Operating on strings¶
The meaning of an expression depends both upon its structure and the types of values that are being combined. So, for instance, adding two strings together produces another string. This expression is still an addition expression, but it is combining a different type of value.
"data" + "science"
Addition is completely literal; it combines these two strings together without regard for their contents. It doesn't add a space because these are different words; that's up to the programmer (you) to specify.
"data" + " " + "science"
Single and double quotes can both be used to create strings: 'hi'
and "hi"
are identical expressions. Double quotes are often preferred because they allow you to include apostrophes inside of strings.
"This won't work with a single-quoted string!"
Why not? Try it out.
Converting other values to strings¶
Anything can be described in text, so it's possible to convert any value to a string. The str
function (which confusingly has the same name as the str
type) returns a string representation of any value.
str(1 + 1)
Using this function, strings can be constructed that have embedded values.
str(1 + 1) + " cool " + str(4 / 1) + " school"
Converting strings to other values¶
Sometimes, the text in a string describes another kind of value. In particular, numerical data often comes in the form of text that contains numbers. For example, "2"
looks like a number. However, its type is str
, and Python treats it like any other string.
"2" + "2"
If we want to work with this kind of data as a number, we can use the int
and float
functions:
int("2")
float("2.2")
int("2") + int("2")
Of course, many strings don't look like numbers, and Python will complain if you attempt to convert them to numbers:
int("two")
int("2 cool")