Python Strings: Spinning Yarns

As the students used to say to Mr. Kotter: "Welcome back, welcome back, welcome back." In our previous article we talked some more about how to manipulate strings in Python, leaving off with indexing and slicing. Here, we will pick up again with slicing, using it to “change” the contents of a string.

I say "change" in quotation marks because technically strings are immutable, or in less fancy speak, they are like a hippy’s views of the world — they cannot be changed. Unless of course the 1980s and big business rolls around and those hippies discover the wonderful world of free commerce. You get a job you damn hippy!

Just a side note: hippy is not in my Word dictionary, but Lippy, Tippy, Pippy, and Hippo are for some reason.

Tricking the Computer

I don’t know why we have to trick the computer in order to change a string. I mean, why couldn’t strings just be changeable? Because computer programmers like to mess with you, that’s why, especially the ones that create languages and specifically the ones that create open source languages. They don’t make money, so their sole satisfaction is to confound you. And let’s face it, that isn’t too hard to do.

Here is how we "change" those hippy strings. Note that we will be writing this code at the command prompt of our Python shell.


>>> woodstock=’I am a hippy’

>>> wallstreet=woodstock[0:7] + ‘yuppie’

>>> print wallstreet

I am a yuppie

Let’s have a little more fun with it. In the following example, we will assign the alphabet to a variable named, well, alphabet, then use slicing to print out the coolest name in history. Note that the index number for the string begins with 0, so for instance, a is index 0, b is in index 1, and z is index 25, as opposed to 26.


>>> alphabet=’abcdefghijklmnopqrstuvwxyz’

>>> name=alphabet[9]+alphabet[0]+alphabet[12]+alphabet[4]+alphabet[18]

>>> print name

james

{mospagebreak title=The Interpolation Operator}

When we wish to specify what happens to a value when we insert it into a string, we can do so using the interpolation operator(%). We can use this to insert data inside of a string, determine how many digits are displayed next to a decimal, determine how much space to allow for the data (known as the minimum field width), and more.

Here is a list of possible formatting code you can insert after the interpolation operator(%):


  • %c – used for a single character

  • %d and %i – used for signed integer decimals

  • %f and %F – used for floating point decimals

  • %r – represents the data

  • %% – used as an escape character for the percentage symbol

To insert a single character into a string, we can do so, as described above, using %c. Here it is in code:

missing=’F’

print ‘Which character is missing from the following sequence?’

print ‘A B C D E %c G H I J K L M N O P Q R S T U V W X Y Z’ %missing

When the code prints, it replaces the code %c with the value in our variable, missing, which in this instance is ‘F’. Here is the result:

  Which character is missing from the following sequence?

  A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

If we wanted to insert an entire word or sentence, or string, we could do that as well by using %s:


hawtness=’James Payne’

print "And the winner of this years Uber Hawtness award goes to….*drumroll*"

print "The magnanimous, heroic, super-strong, giant-brained, whicka whicka %s ! Whoeee!" %hawtness

In this code, the program sees the %s and replaces it with the value stored in the variable hawtness. The result is:

  And the winner of this years Uber Hawtness award goes to….*drumroll*

  The magnanimous, heroic, super-strong, giant-brained, whicka whicka James   Payne ! Whoeee!

We can, of course, also insert multiple words into our string, using the following method:


hawtness=’James Payne’

gf=’Angelina Jolie’

name=’Jamesalina’

print ‘Here comes the hot new hollywood couple now.’

print ‘%s in an Armani suit, looking dashing and %s in a birthday suit as %s demands it!’ % (hawtness, gf, hawtness)

print ‘As a couple we dub thee…%s’ %name

This displays:

  Here comes the hot new hollywood couple now.

  James Payne in an Armani suit, looking dashing and Angelina Jolie in a birthday suit as James Payne demands it!

  As a couple we dub thee…Jamesalina

The technique works for characters as well:


first=’a’

second=’b’

third=’c’

fourth=’d’

fifth=’e’

sixth=’f’

seventh=’g’

eighth=’h’

print ‘Here are the first eight letters of the alphabet…’

print ‘%c %c %c %c %c %c %c %c’ % (first, second, third, fourth, fifth, sixth, seventh, eighth)

And the result:

  Here are the first eight letters of the alphabet…

  a b c d e f g h

{mospagebreak title=Changing Strings with Methods}

We can use various methods to change the data in a string. We touched on slicing and concatenation earlier in the article, and I am going to talk about it just a little more here. Before, we replaced an entire word; this time we will only replace part of a word:

speech=’A toast, to bread, whom without there would be no taste’

what=’No wait that is not right’

print speech

print what

speech=speech[0:51] + ‘oa’ + speech[52:54]

print speech

Which would produce the following output:

  A toast, to bread, whom without there would be no taste

  No wait that is not right

  A toast, to bread, whom without there would be no toast

We could also use the replace method, which might prove to be a little easier:


speech=’A toast, to bread, whom without there would be no taste’

what=’No wait that is not right’

print speech

print what

speech=speech.replace(‘taste’,’toast’)

print speech

Resulting in:

  A toast, to bread, whom without there would be no taste

  No wait that is not right

  A toast, to bread, whom without there would be no toast

This would also be handy if, say, a certain writer by the name of James Payne began dating your mother:


oldFather=’Your father is named…whatshisname…’

print oldFather

oldFather=oldFather.replace(‘whatshisname’, ‘James Payne the new Hawtness’)

print oldFather

And the shocking results:

  Your father is named…whatshisname…

  Your father is named…James Payne the new Hawtness…

{mospagebreak title=Dealing with Multiple Words}

Here is an example where a word appears a number of times:


story=’It was a dark and stormy night. There was no light, so it was really dark. I mean you could not see anything. We are talking baby chimpanzee trying to wake up its dead mother dark. Dark.’

print story

story=story.replace(‘dark’, ‘light’)

print story

When we run the code, this is what we get:

  It was a dark and stormy night. There was no light, so it was really dark. I mean you could not see anything. We are talking baby chimpanzee trying to wake up its dead mother dark. Dark.

  It was a light and stormy night. There was no light, so it was really light. I mean you could not see anything. We are talking baby chimpanzee trying to wake up its dead mother light. Dark.

As you can see, it replaced all instances of the word dark, except the one with the capital D, with light.

This could of course be a problem if we only wanted to replace one specific dark. What if we wanted to change the first word ‘dark’ to black only? Here is how we would do so:


story=’It was a dark and stormy night. There was no light, so it was really dark. I mean you could not see anything. We are talking baby chimpanzee trying to wake up its dead mother dark. Dark.’

print story

where=story.find(‘dark’)

print where

story=story[:where] + ‘black and ‘ + story[(where+9):]

print story

Resulting in:

  It was a dark and stormy night. There was no light, so it was really dark. I mean you could not see anything. We are talking baby chimpanzee trying to wake up its dead mother dark. Dark.

  9

  It was a black and stormy night. There was no light, so it was really dark. I mean you could not see anything. We are talking baby chimpanzee trying to wake up its dead mother dark. Dark.

If we only wanted to replace one of the ‘dark’ words, we could do it this way as well: (type this into your command prompt)


>>> story.replace(‘dark’,’black’,1)

‘It was a black and stormy night. There was no light, so it was really dark. I mean you could not see anything. We are talking baby chimpanzee trying to wake up its dead mother dark. Dark.’

Well that’s all the time we have for now. In our upcoming tutorials we will discuss the various string methods in depth and take a look at math and numbers in Python.

Till then…

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan