Practical Python String Methods

In this article we will look at some practical uses of Python string methods to manipulate text.

Much of the the power of the internet depends on the ability to manipulate strings, since web pages are generally transmitted as HTML strings.

Definition of a String in Python

A string is a data type consisting of a collection of Unicode characters. In simple terms, it is basically “some text.”

Strings in python are surrounded by either single quotation marks or double quotation marks.

Python print() function.

print() is a very powerful Python function that can do much more than just display output.

For a very basic example of how to use strings and print(), see below. First we create a string and then output to the screen.

my_string = "I am text."
print(my_string)

Output:

I am text.

In the next example, notice that the input() statement receives data as a string, which can cause unexpected bugs. We are also using two different ways to separate multiple items in a print() statement: comma separation and what is known as concatenation, where we use + to mean “joined together” in the context of strings.

To convert the string my_input to an actual number (integer), you would use int(my_input)

my_input = input("Enter a number: ")
print("Did you expect", my_input * 2 + "?")

Example output:

Enter a number: 5
Did you expect 55?

We can also use the end argument to print() to define what happens at the end of the output. Usually it goes onto a new line, but in the example below we have asked each item to be followed by a comma instead of a newline.

for i in range(1, int(my_input) + 1):
    print(i, "Mississippi", end=",")

Output:

1 Mississippi,2 Mississippi,3 Mississippi,4 Mississippi,5 Mississippi,

Python len() function

The len() function is very straightforward. Take a string (in this case) and tell us how many characters it contains.

print()
print("There are", len(my_string), "characters in the variable named \"my_string\".")

Output:

There are 10 characters in the variable named "my_string".

Notice that the end="," from the previous print() command is still in effect, which is why I have put the extra print() command before continuing.

Did you notice those \ characters? These allowed us to use " without python thinking we wanted to end our string. This is an example of an escape character, and they important to know about. Two other common ones are \n (new line) and \t (tab).

Feed your Brain with these Beginner Python books on Amazon

As an Amazon Associate I earn from qualifying purchases.

Python F-Strings

F-strings are cool. They have been around since Python 3.6 and make working with strings a lot easier than it used to be. They actually come with their own little mini-language for advanced formatting, but here we’ll just look at basic usage:

substitute_me = "eat me."
print(f"On the table was a bottle labeled \"{substitute_me}\"")

num_bottles = 10
print(f"There were {num_bottles} green bottles, sitting on the wall.")

Output:

On the table was a bottle labelled "eat me."
There were 10 green bottles, sitting on the wall.

In the above examples, we used a variable between {} braces and the value was substituted into the string. Notice how we didn’t need to worry about the data type. num_bottles was an integer, but the f-string handled the conversion to a string for us.

You maybe be able to see how we could use f-strings inside a loop to make a simple “Ten green bottles program.” Have a go now if you like.

Python .split() Method

Sometimes we want to convert our string into individual components contained in a list. This enables us to perform various transformations on the component elements, as in for example the Caesar Cipher, which I will cover in a future article.

The way to perform this splitting is with the .split() method. Notice there is a difference here from the examples above. Whereas print() and len() were functions, called using the function name followed by an argument in parentheses, many of the things we can do with strings are in fact methods of string objects. Don’t worry if this doesn’t mean much to you at this stage. The important point is that the syntax for many string operations is my_string.do_something().

The syntax for many string operations is my_string.do_something().

my_string = "these are some words"
my_list = my_string.split()
print(my_list)

Output:

['these', 'are', 'some', 'words']

By default the split() method splits on white space. You can pass an argument to split in another character.

Python .join() Method

It’s natural to wonder how to joint a list back together… The syntax for this can seem a little odd until you get used to it. The join method in Python is a string method which connects elements of an iterable structure, such as a list using a particular string as the connector.

Here’s a couple of examples:

print(" ".join(['these', 'are', 'some', 'words']))
print(":".join(['these', 'are', 'some', 'words']))

Output:

these are some words
these:are:some:words

Like so many things when learning Python, the best way to gain confidence and competence with the .join() method is with practice.

Other Python String Methods

There are many Python string methods which you may wish to explore.

A couple of really useful ones, which are often used to “normalize” input from console applications or web forms are:

  • .upper()
  • .lower()
print("I wAs MixED caSE".lower())

Output:

i was mixed case

This article has explored some important string methods is Python. There are many more available, but the ones here provide a good start and are an important part of anyone’s Python toolkit.

Happy computing!

Sharing is caring!

Leave a Reply

Your email address will not be published.