Knowing how to work with strings is essential in any programming language. Today, we will cover strings in Python: what they are, how to find an index in a string, and which methods exist for working with indexes.
Strings are sequences of character data that can be indexed like any other sequence type in Python. To define a string, you enclose a sequence of characters (letters, numbers, spaces, punctuation marks, etc.) in single, double, or triple quotes. The indexing of characters starts at zero, and each character in the string has its own index. The index of the last character is one less than the length of the string.
string = 'We love Python!'
If we check the type of the string
variable, we will get: str
.
Numerical indexes can be both positive and negative. To access a character by its index, you simply specify the index in square brackets []
. If you refer to a specific index, you can retrieve the character that corresponds to it:
print('4th character: ', string[4])
Output:
4th character: o
In our string, the character "o" has the index 4
.
If you try to access a character at an index that does not exist in the string, you will get an error:
print('15th character: ', string[15])
Error:
IndexError: string index out of range
To find the maximum index in a string, you can subtract 1 from the length of the string, since indexing starts at 0
:
print('Maximum index in the string: ', len(string) - 1)
Output:
Maximum index in the string: 14
Indexes in Python can also be negative, which means indexing starts from the end of the string:
print('-1st character in the string: ', string[-1])
Output:
-1st character: !
The index -1
corresponds to the last character of the string.
In addition to retrieving a character at a specific index, you can also extract a range of characters from a string—a substring. This is done using the slicing operator, and the resulting portion of the string is called a slice.
print('Characters from index 1 to 6: ', string[1:6])
Output:
Characters from index 1 to 6: e lov
In this example, 1
is the start index, and 6
is the end index. The slice includes characters from index 1 to 5 (the end index is excluded).
If you want to extract a substring starting from index 0
, you can omit the start index:
print('Characters from index 0 to 6: ', string[:6])
Output:
Characters from index 0 to 6: We lov
Similarly, you can omit the end index if you want a slice that goes to the end of the string. Python also allows the use of negative indices when slicing. Negative indices start at -1
from the end of the string and decrease as you move further back:
print('Characters from -7 to -1: ', string[-7:-1])
Output:
Characters from -7 to -1: Python
If no start or end indices are provided, the entire string is returned:
print('Full string: ', string[:])
Output:
Full string: We love Python!
Python allows indices that are out of the string’s bounds, in which case the slice is taken up to the end:
print('Characters from 6 to 100: ', string[6:100])
Output:
Characters from 6 to 100: e Python!
You can also use a third parameter when slicing—a step. The step defines how many characters to skip after each character is retrieved. In the examples above, the default step of 1
was used. Here is an example with a step:
print('Substring with a step of 3: ', string[0:10:3])
Output:
Substring with a step of 3: Wley
This returns every third character from the first 10 characters: "We love Python!".
You can even use a step without specifying the start or end, which will create a substring using every nth character from the entire string:
print('Substring with a step of 3: ', string[::3])
Output:
Substring with a step of 3: Wleyo
The step can also be negative, which allows slicing in reverse order.
Python has several methods for counting and retrieving indexes within a string. One of the methods we’ve already covered is len(string)
—which returns the length of the string.
In addition to getting the length, you can also count the occurrences of a character or substring using the count()
method:
print('Number of occurrences of "e":', string.count('e'))
Output:
Number of occurrences of "e": 2
Another method lets you find the index of a character or substring within the original string:
print('Index of character "e":', string.find('e'))
Output:
Index of character "e": 1
The first occurrence of the character "e" is at index 1
. If the element is not found, the method returns -1
. When searching for a substring, the method returns the index of its first character:
print('Index of substring "love":', string.find('love'))
Output:
Index of substring "love": 3
To search for a substring starting from a specific index range, you can specify the range:
print('Index of character "e" between index 4 and 9:', string.find('e', 4, 9))
Output:
Index of character "e": 6
To get the highest index of an element in the string, you can use the rfind()
method, which works like find()
but returns the last occurrence of the element:
print('Last occurrence of "e":', string.rfind('e'))
For finding a substring, you can use index()
and rindex()
, which work similarly to find()
and rfind()
, but raise an error if the substring is not found:
ValueError: substring not found
In this tutorial, we covered the characteristics of string data types, indexing, and slicing in Python 3. These fundamental concepts are useful for a wide range of tasks in one of the most popular programming languages. You can find more information in the documentation and Hostman tutorials.
On our app platform you can find Python applications, such as Celery, Django, FastAPI and Flask.