Login

Python: Stringing You Along

If you have ever programmed before, or are a ninety-year-old lady, or a cat, then you know how useful strings are. If you have been reading these articles, you will know that a string is a character, a sentence, a paragraph, a book, etc. If you haven’t been reading these articles, then you’re missing an important part of your education as a programmer. Don’t keep yourself in the dark; start reading!

In this epic article we will cover the various ways to manipulate string objects in Python. These range from sorting and indexing to some of the built-in string methods. So put down those knitting tools, kick that cat across the room like a football, and let’s be like Olivia Newton-John (i.e., let’s get physical).

The Basics

Here we are going to cover some of the basics of strings. If you need a refresher on them, you can read along. Or, if you are a string writing pro, feel free to skip over this section, or read it and get real bored and send me hate mail. Whichever you choose is fine.

Printing a string

#!/usr/local/bin/python

print "Here are some samples of basic strings:"

print " "

print "Now you know and knowing is half the battle"

print "A"

print "9"

print "%#$@!"

print "It was the best of times, it was the worst of times,"

print "It was the age of wisdom, it was the age of foolishness"

print "It was the epoch of belief, it was the epoch of incredulity"

print "It was the season of Light, it was the season of Darkness"

print "This quote goes on forever…"

Storing Strings in Variables and Printing Them

#!/usr/local/bin/python

apple = "Fudgebuckets"

sentence="Look at this! It’s a sentence! No wait…it’s two sentences!"

print apple

print sentence

Printing Quoted Text

#!/usr/local/bin/python

print "And he said to me, ‘I pity the fool!’ "

print ‘And I quote: "Quit yo jibba-jabba!"’

print " "

print "Notice that it is best to use single quotes when you want to do double quotes"

print "And double quotes when you want to do single quotes"

{mospagebreak title=Making Text Appear Exactly As You Typed It}

#!/usr/local/bin/python

two_cities= """

It was the best of times, it was the worst of times, it was the age of wisdom,

it was the age of

foolishness

it was the epoch of belief, it was the epoch of incredulity, it was the season

of Light, it was the season

of Darkness,

it was the spring of hope, it was the winter of despair, we had everything

before us,

we had nothing

before us,

we were all going direct to heaven, we were all going direct the

other way-

in short, the period was so far like the present period, that some

of its noisiest

authorities

insisted on its being received, for good or for evil, in the superlative

degree

of comparison

only.

"""

print "Look out! Dickens is back!"

print " "

print two_cities

The result of this code:

Look out! Dickens is back!

It was the best of times, it was the worst of times, it was the age of wisdom,

it was the age of

foolishness

it was the epoch of belief, it was the epoch of incredulity, it was the season

of Light, it was the season

of Darkness,

it was the spring of hope, it was the winter of despair, we had everything

before us,

we had nothing

before us,

we were all going direct to heaven, we were all going direct the

other way-

in short, the period was so far like the present period, that some

of its noisiest

authorities

insisted on its being received, for good or for evil, in the superlative

degree

of comparison

only.

{mospagebreak title=Other Ways to Span Text}

We saw above that you can use triple double quotes (or even triple single quotes if you want) to print your text exactly as it appears. You can also control how many lines (or not) your text will span. Below is some example code demonstrating this:

#!/usr/local/bin/python

print "This is how you turn multiple lines into one line:"

print " "

multiple = "Here is a whole bunch of text that will

fit on one line

when we are through"

print multiple

print "The following text will print on four lines: "

print "Hellonhownarenyou?"

print "We can also use parentheses to add several strings on separate lines into one:"

three_strings = ("I like "

" to eat"

" pancakes")

print three_strings

print "Here is how we create a space between linesn"

print "By using an escape character"

This results in:

This is how you turn multiple lines into one line:

Here is a whole bunch of text that will fit on one line when we are through

The following text will print on four lines:

Hello

how

are

you?

We can also use parentheses to add several strings on separate lines into one:

I like to eat pancakes

Here is how we create a space between lines

By using an escape character

Escaping

Escaping allows you to print characters that are normally reserved for other purposes. To Python, a double quote normally signifies either the start of a string or the end of a string. If you want to print the quote so it shows up, you can encase it in another quote as described above (the preferred method) or you can use an escape character, as shown below:

#!/usr/local/bin/python

print "Here is an example of the single quote escape:"

print ‘It’s okay’

print "If you tried it without the escape, it would have returned an error.n"

print "The same with the double quote escape: "

print "He said, "Hi there." "

print " "

print "And of course you met our friend the newline escapenn"

print "Here is the tab escape ttt I’m over here!n"

print "And here is how you escape the backslash\"

This prints out:

Here is an example of the single quote escape:

It’s okay

If you tried it without the escape, it would have returned an error.

The same with the double quote escape:

He said, "Hi there."

And of course you met our friend the newline escape

Here is the tab escape I’m over here!

And here is how you escape the backslash

Here is a table showing some of the Escape characters:

Character

What it Does

Forces text on the following line to fit on the same line

\

Lets you print a backslash

‘

Lets you print a single quote

”

Lets you print a double quote

e

The escape key

n

Creates a space between your next sentence

t

Creates a tabbed space in your string

Getting Raw

Sometimes you want to print text without having to worry about Python interpreting it as an escape code. This can happen if you type a path to a file on a server or your computer. You can use raw strings to accomplish this, by placing an r in front of the first quotation mark, like so:

#!/usr/local/bin/python

print r"C:python25text.py"

This prints out:

C:python25text.py

{mospagebreak title=String Operators}

There are several operators you can use on strings. Here is how some of them work:

#!/usr/local/bin/python

first ="James "

last ="Payne "

truth ="Is a bad mamma jamma"

print "Here is an example of concatenating string variables:"

print first+last+truth

print "n"

print "Here is another example of concatenating strings:"

print "I like it " + "When you call me " + "Big Poppan "

print "And here is an example of how to repeat text with variables:"

print first *3

print "You can also print it on three separate lines:"

print (first + "n") * 3

print "You can also concatenate and repeat (as we did above):"

print (first+last+truth+ "n") * 4

Note that I put a space in my strings. If I had not, the words would be bunched together. Here is the result:

Here is an example of concatenating string variables:

James Payne Is a bad mamma jamma

Here is another example of concatenating strings:

I like it When you call me Big Poppa

And here is an example of how to repeat text with variables:

James James James

You can also print it on three separate lines:

James

James

James

You can also concatenate and repeat (as we did above):

James Payne Is a bad mamma jamma

James Payne Is a bad mamma jamma

James Payne Is a bad mamma jamma

James Payne Is a bad mamma jamma

Well that’s it for this tutorial. We still have more string-a-ma-things to cover, and we will do so in the next article. So come back often and get dat learn on son.