4.1. Assign a Name to a String¶
Create a variable that can store text (a string)
Add (append or concatenate) strings together to create new strings
inputfunction and the concept of a function.
Convert a number into a string to concatenate it to another string
Use dot-notation to invoke functions on string objects
Introduce some string functions like
Show that strings are immutable (don’t change)
4.1.1. Concatenating (Appending) Strings¶
Computers can use names to represent anything. In the last chapter we saw that we can name numbers (declare a variable and set its value to a number) and then do calculations using the names for the numbers. We can also name strings and do calculations with their names, too. A string is a sequence of characters enclosed in a pair of single, double, or triple quotes like
"How are you?", or
'''Why can't you do that?'''. What does it mean to do a calculation on a string? Well, Python uses the
+ symbol to concatenate strings as shown below. Concatenate means to create a new string with all the characters in the first string followed by all of the characters in the second string. This is also called appending strings together.
Now try running this slightly different example.
Blank spaces are not automatically added when you append two strings. If you want a blank space in between two strings then put it there explicitly using a string with just a space in it
" " as shown in ActiveCode1.
Try to run the example below. It should give you errors. Can you fix the errors?
A string is a sequence of characters enclosed in a pair of single, double, or triple quotes. If you start a string with a single quote you must end it with a single quote. If you start a string with a double quote you must end it with a double quote. You must use the
+ operator to append strings together.
We can use the
input function in Python to get your first and last name and then print your full name. A function can take input and returns some value.
4.1.2. Concatenating Strings and Numbers¶
You can print both strings and numbers, and you can concatenate strings using
+, but if you try to concatenate a string and a number you will get an error. The string
"5" is stored very differently than the number
5 in computer memory, so to concatenate the number
5 and a string we need to convert the number into a string first. The
str(num) function will convert a number into a string.
Notice how printing the string
"Fred" prints something different than printing the value of the variable
Fred. Printing the string
"Fred" prints the exact characters in that string. Remember that strings are enclosed in pairs of double or single quotes and when they are printed it will print the exact characters in the string. When you print a variable it will print the value of that variable.
We can update our driving example to print out the cost of the trip with just one
Check your understanding
Discuss topics in this section with classmates.