4 Chapter 4: Strings


3 blue heads in front of many strings of numbers.


Topics Covered:

  • Strings
  • Common String Methods
  • Casting



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 !
Figure 4.1: A Python string.

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.

Python code spelling the phrase "Roar Lions!" and three more lines picking out specific letters from that phrase.
Figure 4.2: Accessing characters within a string.

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.

Python code with the message "I love quizzes" and other code taking out slices of that message.
Figure 4.3: String slices.

You can use the Python len() function to determine the length of a string. The following shows you a couple examples using len():

Python code creating the phrase "Roar Lions!" and code afterwards using len to detet the length of the phrase and a thing.
Figure 4.4: The Python len function.


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:

Python code with the message "I love quizzes", code looking for a specific section of that string, and changing the form of the message.
Figure 4.5: Python string methods.

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:

Different examples of combining string with the plus feature.
Figure 4.6: Combining strings with the plus (+) operator.

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:

Different uses of the imput command.
Figure 4.7: Getting string input from the user.

A sample run of that code is shown next:

A run of the strings of code in Figure 4.7.
Figure 4.8: Program interaction.



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:

Different forms of type casting
Figure 4.9: Examples of 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.

Python code for calculating tips.
Figure 4.10: The tipping program.

When we run this program, a sample interaction appears below:

A run of the strings of code in Figure 4.10.
Figure 4.11: Program interaction.

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”))


Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Python Textbook Copyright © 2022 by Dr. Mark Terwilliger is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book