Chapter 2, Lesson 3 Text

Chapter Two: Working with Data

Lesson Three: Using String Variables

 

Now that you know how to use numeric data types and variables, let's study the use of text values like words and sentences. In most programming languages, including Python, text values and variables are referred to as "strings". String variables are very similar to numeric variables, but there are a few important differences.

String Values and Assignment Statements

string variable stores a series of characters to form a line of text.  A string can hold a single character like "Y" or "N", a word or short phrase like "Stop that bus", or even longer sentences or paragraphs. In Python, a string value is always surrounded by a matched set of single quotes ('Hi') or double quotes ("there").

You can create string variables just like numeric variables. A string assignment statement starts with the variable name on the left, followed by the equals sign (=) and then the quoted string value on the right.

greeting1 = 'Hi'
greeting2 = "there"

Either style (single or double quotes) will work, if you use the same style for one particular string. You can't mix single and double quotes around one string value. It is a good idea to pick one style and stick with it throughout your program. This just makes your code easier to read and understand.

You can also assign the contents of another string variable or any other expression that produces a string. In the example below, we set the greeting2 variable equal to the string value in greeting1. We also set the greetingType variable equal to the results of calling the type() function on greeting2. Can you predict the outcome? Click the "Run Code" button to see the results.

Try It Now

 

Printing Strings

You have already seen how to print lines of text or string values to the screen using the print() function. As a reminder, the print() function can display a hard-coded string value like "I'm Alive!", the contents of a string variable, or any other expression that produces a string result. The type() function produces a string result, for example, so we could pass that result directly into the print() function.

Try It Now

Were you able to predict the output from the above three print() statements?

Combining Strings

You can't perform math operations like subtraction or multiplication on strings, but it is possible to build larger strings by gluing together two or more smaller strings. This gluing operation is called string concatenation. In Python, you can concatenate (or combine) two or more strings using the plus (+) operator.

For example, you might want to build someone’s full name out of two variables that hold the first and last names individually. Let's use the plus (+) sign to concatenate the strings together and then pass the result directly into the print() function.

Try It Now

Notice that the two input strings are glued directly together without any spacing. Python will not automatically add spaces between concatenated strings! Make sure your string values contain the spaces you want, or you will need to add the spaces manually. Let's build a string variable by concatenating together a mixture of hard-coded string values and string variables, and we'll make sure there is a space in-between each word.

Try It Now

Can you see how we ensured spaces between each word in the output message?

When concatenating strings, remember to add spaces between your strings when needed. This can make the difference between a result "like this" and a result "likethis". If you don’t add spaces, your words will run together, which may or may not be what your program intended.

Combining Strings and Numbers

How would you combine a string value with a number to produce a nice message like "Congratulations, your GPA is 4.0"? Let's say the numeric part (4.0) was stored in a floating-point variable named myGPA. You might be tempted to try and use the plus sign (+) to concatenate together the string value "Congratulations, your GPA is " and the myGPA variable. Click "Run Code" in the window below to see what happens.

Try It Now

Well, that didn't work! Instead of the hope-for message, this code produces an error message instead. A message like "TypeError: Can't convert 'float' object to str implicitly" means that you have tried to combine a floating-point value onto a string, but Python was not able to make that conversion automatically.

Python can do many things for you automatically, but if you want to concatenate a number onto a string, you need to first convert that number to a string yourself. Fortunately, you can do this easily with the str() function. When you call the str() function and pass in an integer or floating-point number like 4.0, it will return the matching string like "4.0". You can then safely glue that result onto another string. Run the code below to verify the results.

Try It Now

Great, now we get the expected results! Remember to use the str() function any time you need to convert a number to a string.

Complex Statements

The following statement can be confusing because it has several parts. Let's take some time to make sure you understand each part.

print ("Congratulations, your GPA is " + str(myGPA) )

There are actually at least three different things happening on this single line of code! We are calling a function, str(myGPA), and getting back a string result. Then, that result is concatenated to another string using the plus sign (+) to form a single, long string. Finally, the long string gets passed into the print() statement for display on the screen.

If you prefer to break your coded logic down into a series of smaller statements, that is perfectly fine. The following example does the same thing, using multiple statements that each perform one of the steps. Run the code to verify you get the same results as the single, complex statement.

Try It Now

As you learn to write code, using several smaller statements can be clearer than writing a single statement with multiple parts. When you gain more confidence, you can start combining multiple statements together. The choice is up to you!

 

Work with Me: High Scores

 

In this exercise, you are going to produce a list of high scores for your favorite game. The high score list will contain three entries, each with a name and a score. You will create three sets of name and scorevariables (name1name2name3 and score1score2score3) and then combine each of them in a series of print() statements to display the high score list. The exact choices of names and score values are up to you!

Use the code editor below to write and test your code. The default comments give you more detailed, step-by-step instructions for each section. We've added a few statements to help you get started.

Try It Now

  

 

Our example solution will produce the following output. Your output will depend on the names and scores that you choose.

      High Scores
----------------------
BossLady = 1000
Hunter = 995
AAA = 850

End of Lesson


Last modified: Wednesday, 8 May 2019, 8:01 AM