STRINGS
Topics Covered:
- Strings
- Common String Methods
- Casting
Strings
To computer programmers, a string is simply a sequence of characters. A specific example of one is called a string literal, and is surrounded by quotes. Examples include “Donald Duck”, “35630-1418”, “Florence, Alabama”, and “”. That last example, called an empty string, has no characters. You may have also noticed the second example had numeric digits in it. A string may contain any of the printable characters you see on your keyboard, as well as some characters that don’t show up there.
We use string variables all of the time to store data that is not numeric. The computer stores this data in memory using an encoding called ASCII (American Standard Code for Information Interchange). You might visualize a string as a table, with each slot storing a single character. Take a look at the following 11-character string literal “Roar Lions!”:
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
R | o | a | r | L | i | o | n | s | ! |
Above the table, the position of each character is shown. This position, often called subscript or index, begins counting at zero. While it may seem unnatural to refer to the first position in the table as position 0, that’s a computer-related quirk you’ll see repeatedly, for reasons that are well beyond the scope of this book. The subscript often comes in handy when you need to process or extract information from a string. The following example using Python’s interactive mode illustrates this concept.
Taking a look at this example, you should notice that Idle output the resulting strings with single quotes. You can use single or double quotes for strings. When displaying the 5th character – the character in position 4 – a space is printed. You can use [m:n] to create a substring, or slice, of a string. It returns the string that starts at position m and ends at position n-1.
The following example shows four examples of the slice. The first displays a string beginning at position 3 and goes up to but does not include position 5. The second example displays characters 7 through 10. The third example does not include an ending number after the colon. This will display all characters at position 3 and beyond. The final example is missing the beginning subscript before the colon. All characters before position 5 are displayed.
You can use the Python len() function to determine the length of a string. The following shows you a couple examples using len():
Common String Methods
In chapter one, we mentioned that Python is an object-oriented language. A data item like a string is treated as an object. This means that in addition to storing data like “Roar Lions!”, the string object also has built-in functions, or methods, that it can reference using the name of the string variable followed by a period followed by the function name. The examples below will demonstrate several of the methods provided for string objects:
The find message searches the string for a pattern and returns the position where it matches. The pattern “quiz” was found at position 7. The pattern “Love” was not found so a -1 was returned. Notice that the matching is case-sensitive.
When applied to numbers, the plus (+) operator is used to add the two operands. You can also use this same plus operator with two strings. It will perform string concatenation, which simply means the strings are joined together. When a language defines an operator to perform different functions depending on its operands, this is called operator overloading. It’s intuitive and easy to use, as illustrated below:
In the examples above, you can see how you can apply the plus operator multiple times and it will concatenate the strings from left to right. The example demonstrates how you could use plus operator to combine strings and then store the result to a variable.
As previously mentioned, the input function allows the user to enter information from the keyboard. The result is a string that is usually assigned to a variable. Most of the time, you will want to provide a prompt as a parameter to the function so that the user knows that your program is waiting for some input. Here is an example that shows a few examples:
A sample run of that code is shown next:
Casting
In the previous example, all of the input values were used as strings. When we need the user to enter a number that will be used in an arithmetic expression, we need to use type casting, which is converting from one type to another. Here are a couple of examples from the interactive window that demonstrate type casting:
INTERACTIVE – Fun with strings
Try out the program below to learn more about strings and the string slicing function. Experiment with different inputs and try to predict the output before you run the program.
Don’t forget to tip your wait person!
Now let’s look at a complete example. Suppose we wanted to write a program that asks the user for a restaurant server’s name, amount of restaurant bill, and tip percentage. The program should compute and display the tip amount and the total bill.
When we run this program, a sample interaction appears below:
As you can see from the code, a type cast was needed to convert the meal cost and tip percentage from a float to a string. A type cast was not needed for the wait person since it is already the intended string type.
Chapter Review Exercises:
4.1. Show the output of the Python instructions:
str = “Tigers win the game”
print (len(str))
4.2. Show the output of the Python instructions:
str = “Tigers win the game”
print (str[6:9])
4.3. Show the output of the Python instructions:
str = “Tigers win the game”
print (str.find(“win”))
4.4. Show the output of the Python instructions:
str = “Tigers win the game”
print (str.find(“lose”))
4.5. Show the output of the Python instructions:
str = “Tigers win the game”
print (str.upper())
4.6. Show the output of the Python instructions:
str = “Tigers win the game”
print (str.count(“e”))