Skip to Content

5 String Operators In Python Everyone Needs To Know

5 String Operators In Python Everyone Needs To Know

What are the most common string operators used in Python and why they’re essential to know?

It doesn’t take long when you begin programming in Python to work with strings and to start modifying these strings by using common operators.

Here I’ll look at 5 of the most common string operators I use in my own Python code and how you can use them in your own code.

1. String Concatenation

One of the first questions most new Python programmers seek to perform with strings is combining two or more together. This technique is known as string concatenation.

To concatenate two or more strings together in Python use the + operator as if you were adding two numbers together.

Here’s an example in the Python REPL:

>>> a_string = "Hello "
>>> b_string = "World!"
>>> a_string + b_string
'Hello World'

As you can see from the above example you can easily combine strings together by just placing the + sign between them.

If you try to combine a string with an integer, or some other data type that isn’t a string, you will get a TypeError shown like this:

>>> a_string = "Number "
>>> a_num = 100
>>> a_string + a_num
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

To avoid getting TypeError errors ensure that you are operating with variables that are of the type str, if in doubt use the built-in str() method that converts both variables to a string like so:

>>> a_string = "Number "
>>> a_num = 100
>>> str(a_string) + str(a_num)
'Number 100'

As you can see using the str() method helps to convert a number into a string making it available for combining with another string.

2. String Slicing And Reversing

Next in popularity is slicing up a string. While there is no subtraction (i.e. -) permitted between strings as there is with addition, there is an operator that can help cut a string up and this is the very handy slice operator.

Its structure looks like this and contains three parameters, all of which are optional and have default values if excluded:

[start:stop:step]

The first parameter start is the starting index value of the character in the string you want to begin extraction or capture, remembering that the first character in a string starts with index 0. If the start parameter is left blank the capture begins with the first character, therefore, using 0 may help with readability of your code but is redundant.

The second parameter stop is the ending index value of where capture from the string ends and is exclusive. This means if an index number is placed at this position in the slice operator the capture will not include the character at the index number. If the stop parameter is blank the capture goes to the very end of the string.

The third parameter step is the frequency of capture from the start to the stop index number. If the step parameter is not set the default value is 1.

Here are some examples demonstrating the slice operator:

>>> my_string = "Uncopyrightable"
>>> my_string[::-1]
'elbathgirypocnU'

In this example above you can see I’ve reversed the string by using just the step parameter and entering -1.

>>> my_string = "Uncopyrightable"
>>> my_string[:4]
'Unco'

In this example a simple extraction of the first four characters from a string using the stop parameter only.

>>> my_string = "Uncopyrightable"
>>> my_string[6:-4]
'right'

In this example, you can extract a specific string when setting both the start and stop parameters. A negative number starts the count from the end of the string, with -1 representing the last character in the string, -2 the second last character (etc).

To explore more instances of the slice operator check out these articles: extracting the first and last n characters from a string, removing the last character from a string, removing a file extension from a string.

3. String Expansion

Another popular operator using the multiplication sign * is when you want to expand the contents of a string into all of its individual characters. This is where the multiplication sign is inserted at the beginning of a variable, one containing a string for example, and you want the contents printed in a specific way.

Here’s an example illustrating the asterisk operator:

>>> my_string = "12345"
>>> print(*my_string, sep="\n")
1
2
3
4
5

This operator allows for the expansion of a string into its individual parts being the characters that make up the string itself.

4. String Repetition

Besides using the multiplication sign * at the beginning of a string variable the same sign can be used to multiply an instance of a string. This can be useful when creating a string with a repeating component to it.

Here’s how the string multiplication looks:

>>> my_string = "10" * 5
>>> print(my_string)
1010101010

As you can see from the example above by using the multiplication sign on a string you can repeat the pattern the quantity of times it is being multiplied.

What happens when you multiply by a negative number?

>>> my_string = "Hello" * -1
>>> my_string
''

When multiplying by a negative number it produces a blank or empty string.

5. String Contains

The last operator you will use frequently in your Python coding is the in operator (or its inverse not in) which checks if a string can be found within another string. The result of this operation is a boolean result which confirms the string can be found by returning True or if it cannot be found returning False.

Here’s an example demonstrating this operator:

>>> my_string = "Hello world"
>>> 'Hello' in my_string
True

As the example above shows the string Hello can be found in Hello world you must make sure you are consistent with your case when checking for strings. If case isn’t an issue then you might want to consider using .lower() or .upper() string case methods matching the checking string’s case.

>>> my_string = "Hello world"
>>> 'hello' in my_string.lower()
True

What Operators Cannot Be Used?

Most operators in Python are used with numbers such as modulus % or division / or quotient //, therefore, there are many other operators that cannot be used with strings. As demonstrated above addition and multiplication can be used, but most other common operators like subtraction and division cannot.

Summary

The most popular types of operators used with strings in Python are those which help with concatenation, slicing or reversing, expanding a string into characters, repeating a string multiple times and checking if a string is found in another string.

Master these operators and you will find your Python coding skills improve.