Python: Text Concatenation

Go to Chapter 8 in A Smarter Way.

Consider how we populate a variable with a string:

first_name = "helen"

last_name = 'keller'

Now we can print them:

print(first_name)

print(last_name)

But this isn’t quite right. The names are on separate lines. We need to either remove the line break from the first print call, or make two print calls on one line.

We can in fact “add” two strings together within a print statement in a couple of ways. We can use commas to separate several arguments, and let print output them one at a time:

print(first_name, last_name)

Notice the spacing in the output: print provides it automatically.

Now try:

print(first_name + last_name)

When we’re concatenating strings to put them in a variable the comma-based syntax in print() above won’t work. It’s an operation of the print function. In all other cases, we use the plus sign to concatenate strings.

full_name = first_name + last_name

Again, notice the spacing in the output: you get exactly what you ask for. And you didn’t ask for a space. This is what you need:

full_name = first_name + " " + last_name

Sometimes you’ll need to put print() calls on multiple lines, but you want the output to be on a single line.

In Python 3, you can use this syntax:

print(first_name, end=””)

This won’t work in Python 2.7, but it will if you import the print_function from Python 3:

from __future__ import print_function

(See https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space for more information.)

You will have to declare this import at the top of every script in which you will use this syntax in Python 2.6/2.7.

Now you can do something like this:

print(first_name, end="")

print(last_name)

Notice that this format works fine when you run a script, but doesn’t work so well at the python shell command line. If you want to try it there, use this:

print(first_name, end=""); print(last_name)

Exercises

Go to http://introtopython.org/var_string_num.html#Changing-case and scroll down to Combining strings (concatenation). Study this section.

Go to http://www.asmarterway.com/python/8.html.

  1. Edit your examples.py script.
  2. Make the author’s name at least two variables.
  3. Print the two variables to the same line.
  4. Remember your degree variable? It should still be there. Add another print statement on a new line, but make it print on the same line as the author’s name.