Department of Mathematics

Math 300: Mathematical Computing

Python Strings

Like all modern languages, python has a powerful ability to store and manipulate character strings. This is generally less important to us as mathematicians, but nonetheless we often have to label axes, title plots, and use strings in other ways, so we'll look at a few of the things we can do.

As discussed in the data type page, python can recognize strings entered using any of three types of quotation marks. Once they are entered, they can be manipulated in fairly natural ways using operators that we would ordinarily consider as applying only to arithmetic.

>>>>>> y="Yossarian said, " >>> twice='"I see everything twice!"' >>> y+twice 'Yossarian said, "I see everything twice!"' >>> twice*2 '"I see everything twice!""I see everything twice!"'

We see that we can define two strings as we did on the earlier page, but then concatenate them using a + symbol: in python, adding two strings concatenates them. Multiplying a string by an integer concatenates that string to itself the specified number of times. Do not try to multiply one string by another.

Every string is actually an object in python, with its own associated methods that can return properties of the string, or change the string in various ways.

>>>>>> len(y) 16 >>> y.find('said') 10 >>> y[10] 's' >>> Y=y.replace('said','shouted') >>> Y 'Yossarian shouted, ' >>> Y.upper() 'YOSSARIAN SHOUTED, ' >>> z=Y.lower() >>> z 'yossarian shouted, ' >>> z.capitalize() 'Yossarian shouted, '

One of the methods associated with a string is format. This allows us to create strings on the fly, using the values of variables we might have calculated. In this case, we can specify the string using braces {} where we want to make substitutions according to the order of arguments to format. This is easier to see than to describe.

>>> call="Call me {}." >>> call.format("Ishmael") 'Call me Ishmael.' >>> call.format("maybe") 'Call me maybe.'

We can use more than one set of braces if we like, in which case the arguments to format are substituted in order.

>>> times="It was the {} of times, it was the {} of times." >>> times.format("best","worst") 'It was the best of times, it was the worst of times.' >>> times.format("worst","best") 'It was the worst of times, it was the best of times.'

Assignment C is posted.

The test solution is available.

Department of Mathematics, PO Box 643113, Neill Hall 103, Washington State University, Pullman WA 99164-3113, 509-335-3926, Contact Us
Copyright © 1996-2015 Kevin Cooper