Some string methods

Published

2023-07-31

Some string methods

Python provides us with many tools for manipulating strings. We won’t introduce them all here, but instead we’ll demonstrate a few which we’ll use in programming exercises, and then introduce more as we need them.

First, what is a string method? If you’ve ever programmed in Java or C# or other OOP language, you may be familiar with methods. If not, don’t fret, because the concept isn’t too difficult.

Strings are a type of object in Python. Consider what happens when we ask Python what type the string “Mephistopheles” is.

>>> type('Mephistopheles')
<class 'str'>

What Python is telling us is that “Mephistopheles” is an object of type str.

When the developers of Python defined the types str, int, float, bool, etc. they created classes corresponding to these different types of objects. We won’t cover any object-oriented programming in this book, but you can think of a class as a blueprint for creating objects of a given type. We instantiate an object by making an assignment, for example

n = 42

creates an object of type int, and

s = 'Cheese Shoppe'

creates an object of type str, and so on. The class definitions give Python a blueprint for instantiating objects of these different types.

One of the things classes allow us to do is to define methods that are part of the class definition and which are included with the objects along with their data. Methods are nothing more than functions defined for a class of objects which operate on the data of those objects.

Here’s an example. Let’s create a string object, s

>>> s = 'mephistopheles'

Now, just like we can access individual members of the math module with the member (.) operator (for example, math.pi, math.sqrt(2), math.sin(0.478), etc.) we can access string methods the same way!

For example, the capitalize() method can be called for any string object, and it will return a copy of the string with the first character capitalized (note: this does not modify the string, it just returns a copy of the string).

>>> s = 'mephistopheles'  # note: this is all lower case
>>> s.capitalize()
'Mephistopheles'

Here’s another method: upper() (you can guess what this does).

>>> s = 'mephistopheles'  # note: this is all lower case
>>> s.upper()
'MEPHISTOPHELES'

Now what if we had a string in all upper case, but wanted it in lower case?

>>> s = 'PLEASE STOP YELLING'
>>> s.lower()
'please stop yelling'

As you might imagine, these can come in handy, and there are many more (take a peek at Built-in Types (https://docs.python.org/3/library/stdtypes.html) and scroll down to String Methods if you’re curious).

It is important to keep in mind that these do not alter the string’s value, they only return an altered copy of the string.

>>> s = 'PLEASE STOP YELLING'
>>> s.lower()
'please stop yelling'
>>> s
'PLEASE STOP YELLING'

If you want to use the result returned by these methods you may need to assign the result to a new object or overwrite the value of the current variable, thus:

>>> s = 'PLEASE STOP YELLING'
>>> s = s.lower()
>>> s
'please stop yelling'

This isn’t always necessary, but keep this in mind.

Some applications

Let’s say we wanted to write a program that prompted the user to see if they wish to continue. At some point in our code, we might have something like this:

response = input('Do you wish to continue? Enter "y" ' 
                 'to continue or any other key to abort: ')
if response == 'y':
    # This is where we'd continue whatever we were doing
else:
    # This is where we'd abort

What would happen if the user were to enter upper case ‘Y’? Clearly the user intends to continue, but the comparison

response == 'y'

would return False and the program would abort. That might make for an unhappy user.

We could write

response = input('Do you wish to continue? Enter "y" '
                 'to continue or any other key to abort: ')
if response == 'y':
    # This is where we'd continue whatever we were doing
elif response == 'Y':
    # This is where we'd continue whatever we were doing
else:
    # This is where we'd abort

or

response = input('Do you wish to continue? Enter "y" '
                 'to continue or any other key to abort: ')
if response == 'y' or response == 'Y':
    # This is where we'd continue whatever we were doing
else:
    # This is where we'd abort

Instead, we could use lower() and simplify our code!

response = input('Do you wish to continue? Enter "y" to '
                 'continue or any other key to abort: ')
if response.lower() == 'y':
    # This is where we'd continue whatever we were doing
else:
    # This is where we'd abort

This code (above) behaves the same whether the user enters ‘y’ or ‘Y’, because we convert to lower case before performing the comparison. This is one example of an application for string methods.

Another might be dealing with users that have the CAPS LOCK key on.

name = input('Please enter your name: ')
# Now what if the user enters: 'EGBERT'?
# We can fix that:
name = name.capitalize()
# Now name is 'Egbert'

There are lots of uses.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).