This tutorial explains Python String Methods and Operators with programming examples. Learn about string concatenation, substring, comparison, etc:
Strings are one of the most popular and widely used sequences. For example, this tutorial contains letters, which together form words, sentences, and so on.
In fact, strings are so important that almost all the programming languages we shall come across support this sequence in several ways.
=> Check Here To See A-Z Of Python Training Tutorials
In this tutorial, we shall look at how Python handles this type of sequence under the following topics:
- What are Python Strings
- String Operators
- String Methods
Table of Contents:
Python String Methods And Operators
What Are Python Strings
Python has data types and strings are one such data type, but specifically a textual data type. This string data type is a part of an ordered set of objects called sequences.
In these sequences, we can find lists, tuples, and ranges but in this tutorial, we shall focus on strings that are immutable sequences of characters.
NB: An immutable object is one whose state or elements can’t be changed once created.
Strings are often text data that can be identified by double(“) or single(‘) quotes preceding and ending the text or in short a sequence of characters enclosed in quotes.
Example 1: Define strings with double and single quotes.
>>> text1 = "Hello World!" # string with double quotes >>> text1 'Hello World!' >>> text2 = 'Hello World!' # string with single quotes >>> text2 'Hello World!' >>> text1 == text2 # comparing the two quote forms True
From the above example, python knows that “Hello World!” is a string when it encounters the first quote (single or double), it then identifies the end of that string when it comes across the last quote (single or double).
NB: If we start with one quote form(e.g double), Python will only identify the end of the string when it comes across the same quote form(double in this case). Later we shall see how this can vary using a backslash(escape sequence).
Coming from another programming language like C or Java, at this point, you might wonder how python handles characters. In Python, there is no specific data type dedicated for characters, but rather a character is viewed as a string with a length of one.
Example 2: Define a character in Python.
>>> char = "H" # define our single character string >>> type(char) # check its type <class 'str'> >>> len(char) # check its length 1
We can see from the above example that Python treats a single character or anything enclosed in quotes as a string.
Representing Multiline Strings
One thing to note about python strings is that single and double quotes do not enclose multiline strings on their own, rather a SyntaxError will be raised, therefore to represent a multiline string, we often do so in two ways.
#1) Using An Escape Sequence (Backslash)
Escape sequences that are also known as backslash, are commonly known for adding special characters in strings. However, here we don’t attach the backslash with any special character. We just press the Enter key after it.
Example 3: Define multiline strings using backslash.
about_me = "Hello dear, \ My name is Eyong Kevin Enowanyo. \ I am a software engineer and a technical writer. \ Python is one the programming languages I use. " print(about_me)
Output
NB: The output above is actually a string on a single line.
#2) Using Triple Quotes
By triple quotes, we mean single or double quotes called three times. I.E “”” or ”’.
Example 4: Define newline string using triple quotes.
about_me = """Hello dear, My name is Eyong Kevin Enowanyo. I am a software engineer and a technical writer. Python is one the programming languages I use. """ print(about_me)
Output
One thing which we should note about triple quotes is that it adds to our string a newline character(\n) under the hood. This newline character is added at the end of every single line of string.
In order to see this newline character, let’s switch to our Python shell terminal and run the below code.
Example 5:
>>> test = """hello ... world""" >>> test # execute directly 'hello\nworld' >>> print(test) # execute with print() hello world
From the example above, we notice that executing without the built-in print() function will output our string containing the added newline character.
Before we end this section, it is worth important to note the following:
- Both single and double quotes can be used to form the triple quotes.
- The output of a string on the Python shell terminal is always with a single quote and is enforced by most Python linters. The PEP 8 however doesn’t make a recommendation for this.
String Methods
In Python, there are certain methods implemented to use on strings. These are often available with the string method and often they return a new string or boolean rather than modifying the original string. This is because strings are immutable.
The table below explains a few of these methods with code examples from the Python shell terminal.
There are quite a number of these methods and in this tutorial, we have gone over a couple of them just to show you how to use them. To view an extensive list of these methods, please check out Python methods from Python’s official documentation page.
String Operators
We just saw and uncovered what strings generally are. Now let’s take a look at what operations can be carried out on strings. These operators are often intended to be used as a means of interaction with one or more strings.
We are just going to focus on the 6 most important operators i.e. concatenation, repetition, slicing, indexing, membership, and comparison.
Operations on Strings
Operator | Operation | Description |
---|---|---|
Concatenation | s1 + s2 | Concatenates two strings, s1 and s2. |
Repetition | s * n | Makes n copies of string, s. |
Indexing | s [ i ] | Indexing a string, returning element at index i. |
Slicing | s [ i : j : stride] | Slicing a string from i to j with an optional stride. |
Membership | x in s | Returns True if the element, x is in the string, s. Otherwise False. |
x not in s | Returns True if the element, x is not in the string, x. Otherwise False. | |
Comparison | s1 == s2 | Returns True if string, s1 is the same as string, s2. Otherwise False. |
s1 != s2 | Returns True if string, s1 is not the same as string, s2. Otherwise False. |
#1) (+) Concatenation Operator
Most often when programming, we run into the need to concatenate or join 2 or more strings. The plus operator(+) is used in this respect to join or concatenate two strings.
Unlike in other languages like JavaScript where we can concatenate a string and an integer thanks to type coercion, the concatenation operator in Python only concatenates objects of the same type.
We shall later see how we can use the string join() method to join 2 or more strings.
Example 6: Concatenate two strings.
string1 = "first" # define the first string string2 = "second" # define the second string concatenate_string = string1 + string2 # concatenate the two strings print(concatenate_string) # print the concatenated string
Output:
We mentioned earlier that strings are immutable sequences. In the example above, concatenating the two strings doesn’t modify either of the strings. Instead, the operation takes the two strings “first” and “second” and creates a new string “firstsecond”.
Beginners commonly use this operator to add spaces in between strings. Space here is also a string, but this time it’s just an empty string.
Example 7: Print two strings with space in between.
string1 = "first" # define the first string string2 = "second" # define the second string print(string1 +' '+ string2) # print two strings with a space in between.
Output
#2) (*) The Repetition Operator
This operator is used to return a repeated string a specific number of times. The new string contains the said string the number of times specified. The multiplication operator(*) is used for this purpose.
Say we have a string S, and an integer N. By doing S * N or N * S, we shall end up with S repeated N times.
NB: This operator will raise a TypeError if N is a non-integer value.
Example 8: Make n copies of a string s
string1 = "first." # define our string, s print(string1 * 2) # make 2 copies of s print(3 * string1) # make 3 copies of s print(string1 * 0) # make 0 copies of s print(string1 * -1) # make -1 copies of s
Output
We should notice the last two print functions in the example above. Both actually print empty strings. The last but one operation makes sense as it creates zero copy of the string but the last operation is a bit fishy. However, we should note that multiplying a string by a negative number returns an empty string.
#3) ([i]) String Indexing Operator
Indexing a string, for example, s [ i ] returns the i element of a string. Strings are ordered, zero-based sequences of characters. This makes it possible to access specific characters using numeric values that represent their position in the string.
Zero-based here means that the very first character of a string is located at index 0, the next is 1, and so on.
Example 9: Access individual characters of a string using indexing.
>>> string1 = "first. second" >>> string1 'first. second' >>> string1[0] 'f' >>> string1[5] '.' >>> string1[12] # same as string1[len(string1)-1] 'd' >>> string1[13] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
The last line of code in example 9 above raised the IndexError exception. This is because we can’t access an index that is out of range. The string above has 13 elements(including whitespace). However, since strings are zero-based, the last element can be accessed at index 12(13-1)
We can also use negative indexing. In this case, the lookup will start backward.
Example 10: Access individual characters of a string using negative indexing.
>>> string1 = "first. second" >>> string1[-1] # same as string1[12] 'd' >>> string1[-13] # same as string1[0] 'f'
NB: The figure under the section “Using negative indices for slicing” will elaborate more on negative indices.
#4) ([i:j:stride]) String Slicing Operator
Just like all sequence types, strings support slicing. We can retrieve any character or substring from a string by using s[i: j], where i and j are the start and end(exclusive) points of the slice respectively.
Example 11:
>>> name = "EyongKevin" >>> name[3:6] 'ngK'
Let’s understand the process above with the diagram below:
From the figure above, our slicing starts at index 3 and ends at index 6, but as the endpoint is exclusive, we end up with a substring from index 3 to 5.
NB: We also notice from the figure above that string indices are zero-based i.e. the first character in a string has the index, 0.
While dealing with both the indices, an empty string will be returned if i is greater or equal to j.
Example 12:
>>> name = "EyongKevin" >>> name[3:3] # i == j '' >>> name[5:3] # i > j ''
Different Ways To Slice A String
The String slice operator can be constructed in many ways. Given the formula s [ n : m ], we could do the following:
#1) Omit n
omit n as in s [ : m ]. In this case, our slicing will start at the beginning of the string(index 0) and end at m-1.
Example 13:
>>> name = "EyongKevin" >>> name[:6] 'EyongK'
#2) Omit m
Omit m as in s [n : ]. In this case, our slicing will start at index n to the end of the string i.e. at index len(s) – 1, where len(s) is the length of the string.
Example 14:
>>> name = "EyongKevin" >>> name[3:] 'ngKevin'
#3) Omit both m and n
Omit m and n as in s [ : ]. In this case, our slicing will return the entire string. Unlike with lists, this operation returns a reference to the same object. So, a copy is not created.
Example 15:
>>> name = "EyongKevin" >>> name[:] 'EyongKevin'
#4) Using Negative Indices For Slicing
Negative indices can be used to slice a string. Slicing with negative indices can get confusing without proper understanding. So, before we get into some code examples, let’s understand it with the aid of a diagram.
For negative indices, we start counting backward. -1 references the last character in the string, -2 references the second-to-last character, and so on.
Just as for positive indices, slicing from -n to -m results in a substring starting from –n and ending at (-m-1). With this out of the way, we can write some code to see how it works.
Example 16:
>>> name = "EyongKevin" >>> name[-7: -5] # slice from -7 to -6(-5-1) 'ng' >>> name[-10: -5] # slice from -10 to -6(-5-1) 'Eyong' >>> name[-5: ] # slice from -5 to end of string 'Kevin' >>> name[2: -4] # slice from 2 to -5(-4-1) 'ongK' >>> name[-2: -4] # n > m ''
NB: The last operation returns an empty string because the n index(-2) is greater than the m index(-4).
#5) Using Slides
You can even specify a skip number to the slice. For example, s [ n : m : x ] will tell the slice that from the range starting from n to m, skip every x number of characters. It is by default a skip of 1.
Example 17:
>>> name = "EyongKevin" >>> name[1:8:2] 'ynKv'
Let’s understand the above example using the below diagram:
We can also omit the indices as we saw above.
Example 18:
>>> name = "EyongKevin" >>> name[:8:2] 'Eoge' >>> name[1::3] 'ygv' >>> name[::4] 'Egi'
We can also specify a negative stride value. In this case, the steps are counted backward. Note that, when the stride is negative, n should be greater than m, or else, an empty string will be returned.
Example 19:
>>> name[0:3:-2] # empty string returned because n < m '' >>> name[3:0:-2] 'ny' >>> name[:3:-2] # by default, n = -1 'nvK' >>> name[::-2] # by default, n = -1, m = -10 'nvKny'
Omitting both indices and a negative stride of -1 is a common way of reversing a string.
Example 20:
>>> name = "EyongKevin" >>> name[::-1] 'niveKgnoyE'
#5) (In and Not in) Membership Operator
These operators are often used to check if or if not an element or character exists in a particular string. The in returns True if a character x exists in a given string and False otherwise. The not in returns True if a character x does not exist in a given string and False otherwise.
Example 21: Verify if a certain character exists in a string or not.
>>> greeting = "Hello World!" >>> 'H' in greeting # passed True >>> 'h' in greeting # failed. This operation is case-sensitive. False >>> 'Z' in greeting # failed. 'Z' doesn't exist in False
We should note that the membership operators also work with substrings i.e. we can verify if a substring exists in a string or not.
Example 22: Verify if a substring exists in a string.
>>> greeting = "Hello World!" >>> "He" in greeting True >>> "Hel" in greeting True >>> "Helo" in greeting False >>> "Hello World!" in greeting True
#6) ( == and != ) Comparison Operator
These operators in python just like their name specifies, are used to test the equivalence of two operands, in this case, 2 strings. Just because they return a boolean they are mostly used in conditional statements to evaluate the sameness of two strings.
The == operator returns True when the two said strings are the same and False when the two said strings are not the same.
Example 23: Test the equivalence of two strings with the == operator.
>>> fname = "Enow" >>> lname = "Eyong" >>> fname2 = "enow" >>> lname2 = "Eyong" >>> fname == fname2 # "Enow" == "enow", returns False as it is case-sensitive False >>> lname == lname2 # "Eyong" == "Eyong", returns True True
The != operator returns True when the two said strings are not the same and False when the two said strings are the same.
Example 24: Test the equivalence of two strings with the != operator.
>>> fname = "Enow" >>> lname = "Eyong" >>> fname2 = "enow" >>> fname != fname2 # "Enow" != "enow", return True as they are not the same True >>> lname != lname2 # "Eyong" != "Eyong", return False, as they are equivalent. False
So far we have gone over the most widely used operators on strings in Python. Before we wind up this section, let’s throw some light on the unpacking operation. Strings are iterable, so they can be unpacked as in c1, c2,…cn = s.
We see that we used the assignment operator(=) to perform the unpacking operation. Here, dependent on the right operant, this operator can act either as an assignment or unpacking operator.
Example 25: Unpack a string of vowels.
>>> vowels = "aeiou" >>> v1,v2,v3,v4,v5 = vowels # unpacking >>> v1 'a' >>> v2 'e' >>> v3 'i' >>> v4 'o' >>> v5 'u'
NB: We should be careful while using the unpacking operation. If the left operand doesn’t contain exactly the same number of variables as they are the number of characters in the right operand string, then a ValueError will be raised.
Frequently Asked Questions
Q #1) How do you make a string in Python?
Answer: In Python, strings can be created in several ways. The most common way is using the double(“) or single(‘) quotes, for example, “Hello World” and ‘Hello World’ respectively. Also, we could use the built-in str() function to convert values to strings.
For Example,
>>> str(33) '33'
Q #2) Are strings zero-indexed?
Answer: Strings are zero-indexed in Python. A string’s first character is located at index 0, the next is 1, and so on. Note that, here we refer to a string of length > 0. For an empty string whose length is 0, it can’t be indexed because it contains no element.
Q #3) Can you add strings in Python?
Answer: The terminology commonly used here is concatenation. We can concatenate strings together into a new single string using the plus(+) operator.
>>> string1 = "Hello" >>> string2 = "World" >>> string1 + string2 'HelloWorld'
Q #4) Are strings mutable in Python?
Answer: Python strings are mutable. Once created, it can’t be changed. All functions and methods that operate on a string can’t modify the string. Instead, they return a new string that contains the modifications.
Q #5) How do you reverse a string?
Answer: Python has the built-in reversed() function that can be used to reverse a string. Also, most commonly, slicing with a negative stride is used to reverse a string.
>>> greeting = "hello world" >>> greeting[::-1] 'dlrow olleh'
Conclusion
In this tutorial, we looked at what strings are in Python. We also looked at a few Python string operators including concatenation, repeating, membership, etc.
Lastly, we looked at a few Python string methods where we gave a brief explanation of each method with sample code examples.
=> Visit Here To Learn Python From Scratch