String Methods for Beginners

Strings in Python have many useful methods that let you perform various actions with strings.

Methods are similar to functions; they can be called and, like functions, they get a result. The difference is that methods are tied to a specific data type, so string methods can only be called on strings.

You can see all string methods in our handbook. Here are a few examples of how to call string methods:

string = "Hello world!"
print(string.lower())  # hello world!
print(string.upper())  # HELLO WORLD!

It’s important for beginner programmers to remember that methods do not change the original string. Strings in Python cannot be modified. If you want to change all characters to lowercase, for example, you must assign a new value to the string.

string = "Hello world!"
string = string.lower()

String Indices

Sometimes, you need to select individual characters from a string. In Python, use square brackets for this. The table below shows examples of getting a character from a Python string by its index, stored in the variable string.

Code Result Description
s[0] P First character
s[1] y Second character
s[-1] n Last character
s[-2] o Second to last character

Note that the index number of the first character is [0]. A negative index counts characters from the end of the string. A common mistake: trying to set the index s[12] when there are only six elements in the string. Python will return an error:

IndexError: string index out of range

String Slices

A slice extracts part of a string. It consists of an index and a range. Below are examples with the string:

string = 'абвгдежзик'

Index

0 1 2 3 4 5 6 7 8 9

Character

а б в г д е ж з и к
Code Fragment Result Description
string[2:5] вгд Characters with indices 2, 3, 4
string[: 5] абвгд The first five characters
string[5:] ежзик Characters starting from index 5 to the end
string[-2:] ик The last two characters
string[: ] абвгдежзик The entire string
string[1:7:2] бге Every second character from the second to the sixth
string[: -1] кизжедгвба Reverse step, string in reverse

The basic structure of a slice looks like this: String [start_character : end_character + 1]

Slices do not include the explicit end position of the string. For example, in string[2:5], Python outputs characters with indices 2, 3, and 4, but not the character with index 5.

You can leave the start or end index of the string empty. An empty start index defaults to zero. So, string[:5] outputs the first five characters. In string[5:], Python shows characters starting from index 5 to the end. If you use negative indices, you get characters from the end of the string. For example, string[-2:] gives the last two characters.

There is also an optional third argument indicating the step of the slice. For example, string[1:7:2] takes every second character from indices 1, 3, and 5.