How to Perform String Slicing in Python

In this Python tutorial, I will teach you how to do string slicing in Python.

In my data science project, I had to perform string slicing, where I needed to extract the domain part of the URLs in the dataset. For that, I applied the slicing concepts using Python’s slicing operator.

In this tutorial, I have explained string slicing in Python in detail, using several examples to help you better understand it. I have explained two methods that you can implement to perform string slicing.

So, let’s start,

What is String Slicing in Python

String slicing is an approach that allows you to extract the substring of the given string, not the substring itself, even if you can extract specific characters. In Python, two ways exist to extract a substring from the given string.

First, you can use the slicing operator, colon ‘:’ inside the square brackets ‘[]’; the second method is the slice() function.

This approach is usually used in the field of data analysis and manipulation. Let’s see how to perform string slicing in Python.

String Slicing in Python Using Slicing Operator

As I told you, you can slice the string using the colon ‘:’ within square brackets[]. The complete syntax is given below.

str[start:stop:step]

Where,

  • start: The starting index where the slice begins. The character from which the slicing starts. If omitted, then slicing starts from the beginning by default.
  • stop: The ending index where the slice stops. This is the character where slicing ends. But this character is not included in the slicing operation.
  • step: It is an optional argument determining the increment between each index for slicing.

Now, you are familiar with slicing operators; take a simple example where you have the string ‘I live in the United States’.

str = 'I live in the United States'

Suppose you want to extract or slice the string part ‘I live’. First, you need to count the number of characters, including space (consider space a character), in the part you want to extract; it contains 6 characters.

  • One thing to remember is that slicing starts from index 0, which means the index of the first character in the string is 0, then the second character has an index of 1, and so on for other characters in the string.
READ:  How to Count and Display Vowels in a String in Python? [6 different ways]

As you can see, the word ‘I live’ contains six characters so that the index will go from 0 to 5. However, if sliced from 0 to 5, it will extract only the part ‘I liv’ because the start index is 0 and the end index is 5. From the definition, it doesn’t include the last index in the slicing operation.

So to get a complete substring like ‘I live’, you must start from 0 index to 6. For example, execute the code below.

print(str[0:6])
Basic Example of String Slicing in Python Using Slicing Operator

Look at the output. It exactly extracted the substring ‘I live’ using the index numbers from 0 to 6.

The above code starts the slicing from index 0 and goes to 6; an alternate way is to write it like this.

print(str[:6])

So, both str[0:6] and str[:6] have the same start from index 0. But now your mode has changed, and you want to extract from a specific index number like you want only the substring ‘life’.

So, in this case, you will need to specify the starting index as 3 because in the string ‘I live’, one character takes the letter ‘I’, and the second character is the white space after the letter ‘I’.

As the letter ‘l’ in the ‘live’ starts from index 2 in the string ‘I live in the United States’, the index runs from 2 to 6 to extract the word ‘life’ from the string, as shown below.

print(str[2:6])
String Slicing in Python Using Slicing Operator From Specific Index

Again, it extracted the exact desired word ‘life’; this is how you can use the start and end parameters with a colon to slice specified parts of the string.

But wait, there is one more parameter: ‘ step’. The step means the size of the slicing. If you specify the step as 2, it starts from index 0, then skips the character at index 1, then takes the character at index 2, again skips the character at index 3, and so on.

Overall, all steps are the number of characters you want to skip while slicing the string, and that skipped character will not be included in the final substring.

READ:  Python Check If None

For example, you want to extract the substring ‘I live’ again but skip one character. To understand this, execute the code below.

print(str[0:6:2])
String Slicing in Python Using Slicing Operator From Specific Step Size

Look, it starts from index 0, so it includes the letter ‘I’. Then, it skips a character at index 1, which is a space, moves to index 2 to include it, which is the letter ‘l’, skips index 3, which is the letter ‘ i’, includes index 4, which is the letter ‘v’, and lastly skips index 5, which is the letter ‘e’.

From the output, you can see that it extracts the string ‘Ilv’; if you want to know more, play with these parameters: start, end, and step, and you will better understand how the slicing operation works.

You have worked hard to learn how to perform string slicing using the colon ‘:’ inside the square brackets []. However, there is a reward to pay off your hard work: you can specify the negative index to extract the substring in the backward direction of the string.

That means if you want to start slicing from the end of the string, you can specify a negative index, like -4, which will extract the last four characters of the string.

Let’s consider an example with US cities, and we want just the last three characters of the Python string.

city = 'Los Angeles'

last_three_letters = city[-3:]

print("Last Three Letters:", last_three_letters)
string slicing in python with negative slicing example

Look at the output. You mentioned the start parameter so that the slice string would contain the character with that index number, and you did not mention the stop parameter so that it would go till the end of the Python string.

Thus, it returns the string’s sliced last three characters, ‘les’.

Now, move on to how to do string slicing using the slice() method.

Slicing in Python String Using Slicing() Function

In Python, slicing() is a function that behaves like the slicing operator you learned in the above section. The only difference is that it is a function and accepts the same parameters.

READ:  How Python Convert Dictionary to List [9 Different ways]

The syntax is given below.

slice(start, end, step)

Where function parameters are:

  • start: It is the starting index of the slicing part.
  • end: It is the ending index of the slicing part, but not included in the slice part.
  • step: The step size determines the number of indexes to skip between each index.

For example, suppose you have a list named dates containing dates in the format ‘YYYYMMDD’, and you need to extract only the day and year from each date. Look at the code below and execute it.

dates = ["20240101", "20241225", "20241111"]

year_slice = slice(0, 4)
day_slice = slice(6, 8)

for date in dates:
	year = date[year_slice]
	day = date[day_slice]
	print(f"Year: {year}, Day: {day}")
Slicing in Python String Using Slicing() Function

From the output, the slice() function extracts the year and day of each date. Let’s understand the code part ‘year_slice = slice(0, 4) and day_slice = slice(6, 8)’, creating the two slice objects based on the different start and end indexes.

This means creating the first slice of objects from the index 0 to 4, where index 4 is not included; it goes from 0 to 3. Then, create a second slice object from index 6 to 8, which means the actual index is from index 6 to 7.

Then, a loop starts, which iterates equal to the number of dates in the list using the ‘for date in dates’. It then takes each date and applies the concept of list indexing by passing the objects year_slice and day_slice as indexes to each date to extract the year and day of the date.

Thus, it slices the year and day part of each date in the list and prints it using ‘print(f”Year: {year}, Day: {day}”)’.

This is how you can perform slicing in Python string using the slice() function.

Conclusion

In this Python tutorial, you learned how to do string slicing in Python using the slicing operation ‘[start:end:stop]’ and the slice() function.

You may like to read: