HomePython Page 4 - Python 3.1: Strings and Quotes
Putting Two Strings Together - Python
In this second part of a three-part series that introduces you to Python, you'll learn about the importance of strings, how they work, and why Python uses three different kinds of quote marks. It is excerpted from the book Beginning Python: Using Python 2.6 and Python 3.1,, written by James Payne, Developer Shed Editor-in-Chief (Wrox, 2010; ISBN: 0470414634).
There comes a time in every programmer’s life when they have to combine two or more strings together. This is known as concatenation. For example, let’s say that you have a database consisting of employees ’ first and last names. You may, at some point, wish to print these out as one whole record, instead of as two. In Python, each of these items can be treated as one, as shown here:
> > > ”John”
‘John’
> > > ”Everyman”
‘Everyman’
Try It Out: Using + to Combine Strings
You can use several different methods to join distinct strings together. The first is by using the mathematical approach:
> > > “John” + “Everyman”
‘JohnEveryman’
You could also just skip the + symbol altogether and do it this way:
> > > ”John” “Everyman”
JohnEveryman
As you can see from these examples, both strings were combined; however, Python read the statement literally, and as such, there is no space between the two strings (remember: Python now views them as one string, not two!). So how do you fix this? You can fix it in two simple ways. The first involves adding a space after the first string, in this manner:
> > > ”John “ “Everyman”
John Everyman
I do not recommend this approach, however, because it can be difficult to ascertain that you added a space to the end of John if you ever need to read the code later in the future, say, when you are bleary- eyed and it's four in the morning. The other approach is to simply use a separator, like so:
> > > ”John” + “ “ + “Everyman”
John Everyman
Other reasons exist why you should use this method instead of simply typing in a space that have to do with database storage, but that is covered Chapter 14. Note that you can make any separator you like:
> > > ”John” + “.” + “Everyman”
John.Everyman
Joining Strings with the Print() Function
By default, the print() function is a considerate fellow that inserts the space for you when you print more than one string in a sentence. As you will see, there is no need to use a space separator. Instead, you just separate every string with a comma (,):
> > > Print(“John” , “Everyman”)
John Everyman
Please check back tomorrow for the conclusion to this series.