String Slicing in Python – PythonForBeginners.com

0
41
Set Comprehension in Python - PythonForBeginners.com


Strings are one of the most used data structures in Python. We process all the text data using strings in Python. In this article, we will look at ways to extract a sub-string from a given string using slicing. We will also look at some examples of string slicing to understand it in a better way.

What is String Slicing?

String slicing is the process of taking out a part of a string. The characters in the extracted part may be continuous or they may be present at regular intervals in the original string. 

You can understand string slicing using the following analogy. 

Suppose that you are slicing a loaf of bread into pieces. All the pieces, whatever be their thickness,constitute a slice of the bread. Similarly, We can create slices from a string. The only difference in this analogy is that in case of slicing of bread,the original bread is destroyed after the formation of slices. On the contrary, while slicing a string, the original string remains as it is even after creating new slices.  

Let us take an example. Suppose that we have a string “Pythonforbeginners”.

Different slices of the string can be as follows:

  1. Python”: Here, we have taken the first six characters of the string. You can take any number of continuous characters from the original string starting from any index and the characters will constitute a slice of the string.
  2. nigeb”: Here, we have taken some characters in reverse order. You can take any number of continuous characters from the original string starting from any index in reverse order and the characters will constitute a slice of the string.
  3. Ptof”: Here, we have taken some characters that are present at an interval of 1 position. You can take any number of characters at a fixed interval from the original string starting from any index and the characters will constitute a slice of the string.
  4. sngr”: Here, we have taken some characters that are present at an interval of 2 positions in reverse order. You can take any number of characters at a fixed interval from the original string starting from any index in reverse order and the characters will constitute a slice of the string.

In python there are two ways to create slices of a string. We can create a slice from a string using indexing as well as the built-in slice() method. Let us discuss both the methods one by one.

Slicing using String Indices

We can create a slice from a string using indices of the characters. The syntax for string slicing using indices is string_name [ start_index:end_index:step_size ]. Here, 

  • start_index is the index of the character in the string at which slicing of the string starts.
  • end_index is the index of the character in the string at which the slice of the string is terminated. Here, the end_index is exclusive and the character at end_index will not be included in the sliced string.
  • step_size  is used to determine the indices in the original string that will be included in the sliced string. 
    • A step_size of 1 means that the slice will be created from continuous characters starting from the start_index and ending at the end_index-1 of the original string.
    • step_size of 2 means that we will create a slice of the original string using alternate characters starting from the start_index and ending at the end_index-1 of the original string.
    • A step_size of 3 means that we will select characters after leaving 2 positions in between each character of the original string that has to be included in the sliced string starting from the start_index and ending at the end_index-1 of the original string.
  • If the start_index is greater than end_index and the step_size has a negative value, slicing is done in reverse order.

We can understand the working of the above syntax using the following example.

myString = "Pythonforbeginners"
mySlice = myString[0:6:1]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 5, 1, mySlice))
mySlice = myString[13:8:-1]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 13, 9, -1, mySlice))
mySlice = myString[0:8:2]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 8, 2, mySlice))
mySlice = myString[18:7:-3]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 18, 7, -3, mySlice))

Output:

Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 and step size 1 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at index 9 and step size -1 is 'nigeb'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 8 and step size 2 is 'Ptof'
Slice of string 'Pythonforbeginners' starting at index 18, ending at index 7 and step size -3 is 'sngr'

An alternate syntax for string slicing is that we specify only start_index and end_index as in string_name [ start_index:end_index]. Here, the step_size is taken as 1 and the characters are selected consecutively from start_index to end_index-1 as follows.

myString = "Pythonforbeginners"
mySlice = myString[0:6]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))

Output:

Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'Python'

We can also opt to not specify the start_index and the end_index. In such cases, the default value of start_index is taken as 0 and the default value of end_index is taken as length of the string. You can observe these variations in the following example.

myString = "Pythonforbeginners"
mySlice = myString[:6]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))
mySlice = myString[13:]
print("Slice of string '{}' starting at index {}, ending at last index is '{}'".format(myString, 13, mySlice))

Output:

Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at last index is 'nners'

Slicing using built-in function

Instead of using indices of the character directly, we can use the slice() method. The slice() method takes the start_index, end_index and step_size as input and creates a slice object. The slice object is then passed to the original string as index, which then creates the slice of the original string as follows.

myString = "Pythonforbeginners"
slice_obj = slice(0, 6, 1)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 5, 1,
                                                                                                      mySlice))
slice_obj = slice(13, 8, -1)
mySlice = myString[slice_obj]
print(
    "Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 13, 9, -1,
                                                                                                    mySlice))
slice_obj = slice(0, 8, 2)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 8, 2,
                                                                                                      mySlice))
slice_obj = slice(18, 7, -3)
mySlice = myString[slice_obj]
print(
    "Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 18, 7, -3,
                                                                                                    mySlice))

Output:

Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 and step size 1 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at index 9 and step size -1 is 'nigeb'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 8 and step size 2 is 'Ptof'
Slice of string 'Pythonforbeginners' starting at index 18, ending at index 7 and step size -3 is 'sngr'

You can see that the slice object works in almost the same way that we have used to create a slice from a string using the indices of the characters. You can understand this more clearly using the following examples.

myString = "Pythonforbeginners"
# specify only start and end index
slice_obj = slice(5, 16)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))
# specify only end index
slice_obj = slice(12)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 12, mySlice))

Output:

Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'nforbeginne'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 12 is 'Pythonforbeg'

Conclusion

In this article, we have discussed string slicing in python. We have also looked at different ways to create slices from a given string. To study more about strings in python, you can read this article on string concatenation.

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.



Source link

Leave a reply

Please enter your comment!
Please enter your name here