In this Python tutorial, I will show you what is string slicing in Python with illustrative examples.
A Python string is an ordered collection of characters, and each character in the string has an index value associated with it.
In Python, string indices start at 0, meaning the first character of the string is at index 0, the second character is at index 1, and so on also called positive indexing. Python also allows for negative indexing, where the last character of the string is at index -1, the second last at -2, and so forth.
String Slicing in Python
String slicing is one of the most valuable operations that we can perform in Python, especially when dealing with data analysis and manipulation tasks. It’s a way to extract parts of a Python string, whether they are characters, words, or phrases.
Syntax and Parameters:
String slicing in Python is the method used to retrieve a range of characters in a string. We can slice a Python string using the syntax:
- start: The starting index where the slice starts. The character at that index is included.
- stop: The ending index where the slice stops. The character at that index is excluded.
- step: It is an optional argument that determines the increment between each index for slicing.
Examples of string slicing in Python
There are many different ways to slice a Python string, Let’s see them in examples one by one with an explanation.
Example-1: The basic string slicing in Python
Let’s take a famous USA landmark: “Statue of Liberty”. If we want to get only the name of the statue, we can use string slicing:
landmark = "Statue of Liberty" print(landmark[0:6])
Here, to extract the ‘Statue’ from the Python string, we simply will give a start point(included) and stop point(excluded) and print.
The output is:
This is the basic way to use Python slice string.
Example-2: The missing start or stop point in Python string slicing
Suppose we have a Python string of US postal codes with state prefixes and we want to separate the state prefix from the postal code:
zipcode = 'CA90210' state = zipcode[:2] postal_code = zipcode[2:] print("State:", state) print("Postal Code:", postal_code)
Here, we use slicing to separate the state prefix ‘CA’ and the postal code ‘90210’:
The output is: Here, The [:2] part of this line tells Python to create a slice starting from the beginning of the string (index 0 by default) up to but not including index 2. So this line will assign the value ‘CA’ to the variable state.
And, The [2:] part of this line tells Python to create a slice starting from index 2 of the string and go all the way to the end (the end of the string is the default if no end index is specified). So this line will assign the value ‘90210’ to the variable postal_code.
State: CA Postal Code: 90210
This way even if we do not provide the start or stop point still we can get required output.
Example-3: The Python string slicing with step parameter
Let’s take the USA as a Python string in full form, and try to print every alternate character of the USA string.
USA = 'United States of America' print(USA[::2])
The output is: As we all know if we don’t provide the start or stop parameter then they take their default value. so here [::2] will print:
Uie ttso mrc
This we way use step parameter in Python string slicing.
Example-4: Using Negative indexing in Python string slice
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)
The output is: Here, we have mentioned the start parameter so the slice string will contain the character with that index number, and as we have not mentioned the stop parameter so it will go till the end of the Python string.
Last Three Letters: les
This way we can use negative indexing in Python slicing string.
Example-5: Reverse a string with a Python string slice
For instance, we have a Python string in the name of NY. Let’s try to reverse this string using string slicing.
NY = 'New York' print(NY[::-1])
The output is: We have mentioned the negative step parameter so the slicing will walk backward and will give us the desired output.
This way we can reverse a Python string using string slicing in Python.
Example-6: Use of Python string slice with for loop
Suppose we have a Python string of state abbreviations, and we want to slice out each one:
states = 'CA TX NY FL IL' for i in range(0, len(states), 3): print(states[i:i+2])
The output is:
CA TX NY FL IL
This way we can use python string slicing with for loop.
String slicing is a powerful concept in Python, enabling programmers to extract, manipulate, and analyze substrings from larger string data effectively. We have seen different examples to slice a Python string and some uses.
You may like the following Python tutorial:
- How to split a string using regex in python
- Remove character from string Python
- Find first number in string in Python
- How to remove first character from a string in Python
- How to handle indexerror: string index out of range in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.