Python 3.1: Strings and Quotes

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

If you like what you’re reading here, you can find it at Wrox or purchase the entire book at Amazon.

What is a String?

A string is one of several data types that exist within the Python language. A data type, as the name implies, is a category that a particular type of data fits into. Every type of data you enter into a computer is segregated into one of these data types, whether they be numbers or letters, as is the case in this scenario. Giving data a type allows the computer to determine how to handle the data. For instance, if you want the program to show the mathematical equation 1+1 on a screen, you have to tell it that it is text. Otherwise, the program will interpret the data as a mathematical equation and evaluate it accordingly.

You’ll get more into the different data types and how important it is to define them in a later chapter. For now however, know that a string is a data type that consists of any character, be it a letter, number, symbol, or punctuation mark. Therefore, the following are all examples of strings:

“ Hello, how are you? ”

“ 1+1 ”

“ I ate 4 bananas ”

“ !@#$%^ & *() ”

Why the Quotes?

When you type a string into Python, you do so by preceding it with quotes. Whether these quotes are single ( ‘ ), double( ” ), or triple( " " " ) depends on what you are trying to accomplish. For the most part, you will use single quotes, because it requires less effort (you do not need to hold down the Shift key to create them). Note, however, that they are interchangeable with the double and even triple quotes. Try typing in some strings. After you type in each sentence, press the Enter key to allow Python to evaluate your statement.

Try It Out Entering Strings with Different Quotes

Enter the following strings, keeping in mind the type of quotes (single or double) and the ends of lines (use the Enter key when you see that the end of a line has been reached):

> > > “This is a string using a double quote”

‘This a string using a double quote’

> > > ‘This is a string with a single quote’

‘This is a string with a single quote’

> > > “””This string has three quotes

look at what it can do!”””

‘This string has three quotesnlook at what it can do!’

> > >

In the preceding examples, although the sentences may look different to the human eye, the computer is interpreting them all the same way: that is, as a string. There is a true purpose to having three different quoting methods, which is described next.

{mospagebreak title=Why Three Types of Quotes?}

The reasoning behind having three types of quotes is fairly simple. Let’s say that you want to use a contraction in your sentence, as I have just done. If you type a sentence such as “ I can’t believe it’s not butter ” into the shell, nothing much happens, but when you actually try to get the program to use that string in any way, you will get an error message. To show you what I mean, the following section introduces you to the print() function.

Using the print() Function

A function in Python (and every other programming language) is a tool developers use to save time and make their programs more efficient. Instead of writing the same code over and over again, they store it in a function, and then call upon that function when they need it. Don’t worry too much about functions at the moment; they are covered in greater detail later on. For now, it is enough to know what the term means and how it relates to programming.

The print() function is used whenever you want to print text to the screen. Try the following example in your Python shell:

> > > print(“Hello World!”)

When you press Enter, you should see the following:

Hello World!

You will want to note several things here. First, as you were entering in the print() function, a pop – up appeared, showing you the various options available to you within the function.

Second, the text once more appeared in blue on the next line, but this time without quotation marks around it. This is because unlike in the previous examples, Python actually did something with the data.

Congratulations, you just wrote your first program!

{mospagebreak title=Understanding Different Quotes}

Now that you know how to use the print() function, you can begin to work with the different types of quotes discussed earlier in this chapter. Try the examples from earlier:

> > > print(‘This is a string using a single quote!’)

This is a string using a single quote!

> > > print(“This is a string using a double quote!”)

This is a string using a double quote!

> > > print(“””This string has three quotes!

Look at what it can do!”””)

This string has three quotes

Look at what it can do!

In this example, you see that the single quote ( ‘ ) and double quote ( " ) are interchangeable in those instances. However, when you want to work with a contraction, such as don’t, or if you want to quote someone quoting something, observe what happens:

> > > print(“I said, “Don’t do it”)

When you press Enter to execute the function, you will get the error message: SyntaxError: invalid syntax ( < pyshell#10 > , line 1). I know what you are thinking — “ What happened? I thought double and single quotes are interchangeable. ” Well, they are for the most part. However, when you try to mix them, it can often end up in a syntax error, meaning that your code has been entered incorrectly, and Python doesn’t know what the heck you are trying to say.

What really happens here is that Python sees your first double quote and interprets that as the beginning of your string. When it encounters the double quote before the word Don’t , it sees it as the end of the string. Therefore, the letters on make no sense to Python, because they are not part of the string. The string doesn’t begin again until you get to the single quote before the t .

There is a simple solution to this, known as an escape. Retry the preceding code, adding an escape

character to this string:

> > > print(“I said, ”Don’t do it”)

I said, “Don’t do it

This time, your code worked. When Python saw the backslash (), or escape character, it knew to treat the double quote as a character, and not as a data type indicator. As you may have noticed, however, there is still one last problem with this line of code. See the missing double quote at the end of your results? To get Python to print the double quote at the end of the sentence, you simply add another escape character and a second double quote, like so:

> > > print(“I said, ”Don’t do it””)

I said, “Don’t do it”

Finally, let’s take a moment to discuss the triple quote. You briefly saw its usage earlier. In that example, you saw that the triple quote allows you to write some text on multiple lines, without being processed until you close it with another triple quote. This technique is useful if you have a large amount of data that you do not wish to print on one line, or if you want to create line breaks within your code. Here, in the next example, you write a poem using this method:

> > > print(“””Roses are red

Violets are blue

I just printed multiples lines

And you did too!”””)

Roses are red

Violets are blue

I just printed multiple lines

And you did too!

There is another way to print text on multiple lines using the newline ( n ) escape character, which is the most common of all the escape characters. I’ll show it to you here briefly, and come back to discuss it in more depth in a later chapter. Try this code out:

> > > print(“Roses are red n Violets are blue n

I just printed multiple

lines n And you did too!”)

Roses are red

Violets are blue

I just printed multiple lines

And you did too!

As you can see, the results are the same. Which you use is up to you, but the newline escape is probably more efficient and easier to read.

{mospagebreak title=Putting Two Strings Together} 

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”


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


You could also just skip the + symbol altogether and do it this way:

> > > ”John” “Everyman”


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”


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.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye