Strings#
What about letters?#
Up until now, all the data that we have been working with in Python has been numerical: we have been dealing with numbers. So what about letters?
Words, or more generally, collections of individual letters/characters are referred to as strings in Python (and in many other programming languages). String syntax in Python is relatively simple, we just need to enclose whatever letters we want in quotes:
print('Hello world!')
Hello world!
Above we have used single quotes, but we can also use double quotes:
print("Hello world!")
Hello world!
What we cannot do, is open a string with one type of quotation mark, and end it with another:
a_syntactically_invalid_string = 'This string is not valid syntax!"
print(a_syntactically_invalid_string)
Cell In[3], line 1
a_syntactically_invalid_string = 'This string is not valid syntax!"
^
SyntaxError: unterminated string literal (detected at line 1)
Error
There are many different kinds of errors that you may encounter in Python. The example above is a SyntaxError, which means that the code we are trying to run is not valid Python. In other words, it’s not just that our code doesn’t do what we want it to do, it literally does not make sense to the Python interpreter. It’s like we’re trying to speak to someone in a language that they do not understand!
Notice that the error message tells us which line is causing the problem. Here we are informed that line 1 is causing the SyntaxError, in fact the error message even specifies that the syntax problem is an unterminated string literal
.
We will return to errors in more detail later, they may be frustrating at times, but they are also immensely useful!
It’s worth emphasising that you can use double quotation marks within a string that starts and ends with a single quotation mark:
a_valid_string = 'This string is valid Python, despite the "double quotes" in the middle!'
print(a_valid_string)
This string is valid Python, despite the "double quotes" in the middle!
Vice versa, we can include single quotes in a string (for example to use an apostrophe) that begins and finishes with a double quotation mark:
another_valid_string = "This is also valid Python, isn't that wonderful!"
print(another_valid_string)
This is also valid Python, isn't that wonderful!
What if we want to include quotation marks in a string that starts and ends with those same quotation marks? This can be accomplished with a backslack \
which is used to “escape” the desired character:
another_silly_string = 'This string will raise a 'SyntaxError'!'
print(another_silly_string)
Cell In[6], line 1
another_silly_string = 'This string will raise a 'SyntaxError'!'
^
SyntaxError: invalid syntax
a_less_silly_string = 'This string will not raise a \'SyntaxError\'!'
print(a_less_silly_string)
This string will not raise a 'SyntaxError'!
Exercise#
Okay so we’ve learnt about strings - what can we do with them?
Try out the following operations in Python:
Adding two strings together with the
+
operator.Subtracting one string from another with the
-
operator.Adding a string to a number with the
+
operator.Multiplying two strings together with the
*
operator.Multiplying a string by a float (a number with a decimal point) with the
*
operator.Multiplying a string by an integer with the
*
operator.
Caution
Some of these operations will cause errors - this is expected and entirely intentional. When you get an error, try to understand why your code does not run: does the operation you are asking Python to do make sense?
f-strings#
Sometimes we want the content of a string to be generated programatically. All of the strings above have been typed out in full, we have supplied every letter manually and directly. Similar to how use learnt to use variables to avoid manually inputting numbers multiple times, we can apply a similar logic to generate strings with code. For example, imagine that we have just calculated the number of molecules in a tiny bubble of gas as \(N_{\mathrm{mol}} = 4.09 \times 10^{-5}\). We could print this information directly:
N_molecules = 4.09e-5 # From some previous calculation
print('There are 4.09e-5 molecules in the bubble of gas.')
There are 4.09e-5 molecules in the bubble of gas.
Tip
The text following the #
in the code above is a comment. Comments are brief messages which can help you to document your code, making it easier for someone else (or your future self) to understand what your code is supposed to do.
Or we can use an f-string to generate the string programatically:
print(f'There are {N_molecules} molecules in the bubble of gas.')
There are 4.09e-05 molecules in the bubble of gas.
The syntax for creating an f-string can be written generically as:
f'To insert the value of a variable, you use curly brackets: {name_of_variable}!'
Whatever variable you put in the curly brackets will be replaced by the value stored in it when the string is printed to the screen (so long as an f
directly preceeds the string).