Python Slice Operator- Free Python Tutorials

To extract a part of the string we use the python slice operator. We use it to create sub strings of a string. We access each character using its index number. The python slice operator separates the starting index and last index. The characters within this range get printed as output. The python slice operator helps us by manipulating strings and provides flexibility.

Note:– In Python, the index numbers begin from 0.


Index numbers in python

  • For printing characters present at particular index we simply use their index numbers.
  • Indexes in Python can be negative as well as positive. Left to right is taken as positive index whereas the right to left is a negative index which starts with -1. 

Example Program :-

>>> str= ‘meow’

>>> str[2]

Output : ‘o’


>>> str= ‘meow’

>>> str[-1]

Output : ‘w’

In the above programs, we use the index numbers to print the respective characters.

  • When we try to access any index which is not present then we get an error stating the same.

Example:-

>>> str= ‘meow’

>>> str[5]

Output : IndexError: string index out of range

Here, in this program, we try to print the character at index 5 but since that index does not exist thus it throws an index error.


The syntax for slicing –

variable name[starting index : last index]

  • This will return a substring from the starting index to the [ last-1 ] index.

Example Program :-

>>>name= ‘Tannavi’

>>>print(name[1:3])

Output : an

In the above program, we use the slicing operator to extract a substring of the string name. We take the starting index as 1 and the last index as 3.

Note  – If we do not specify the last index then the substring will get printed beginning from the starting index specified to the last index automatically.

Example Program :-

>>>name= ‘Tannavi’

>>>print(name[1:])

Output : annavi

Here in the program above, we don’t specify an ending index so the compiler by default takes the last index as the ending index.


Also, if we do not specify the starting index then the substring will get printed beginning automatically from the first index to the last index specified. Have a look at below program.

Example Program :-

>>>name= ‘Tannavi’

>>>print(name[:4])

Output : Tanna

In this program, we take a string literal named name and then print its substring using the slice operator. Here we don’t specify a starting index so the compiler by default takes the beginning index as the starting index.


If we do not specify both the first and the last index then the substring will be the same as the string. Have a look at below program.

Example:-

>>>name= ‘Tannavi’

>>>print(name[:])

Output : Tannavi

In the above code, both the starting and ending indexes are not specified so the entire string ‘name’ gets printed as the substring.


However, these won’t work the same way as it did if we try it with negative indexes. This is because the starting index must be smaller than the last index.Have a look at below program.

Example:-

>>>name= ‘Tannavi’

>>>print(name[-1:-3])

Output  : ‘ ’

We try to take a starting index and ending index just like we did in the case of positive indexes. But this yields no output.


  • To counter this problem we write the lesser negative number followed by the greater negative number.Have a look at below program.

Example:-

>>>name= ‘Tannavi’

>>>print(name[-5:-1])

Output : nnav

Program Description – We take the starting index as a more negative number and ending index as a less negative number to get a proper output.


While using the slice operator if we enter an index which is out of bounds then it will automatically take the ending point to be the last index.Have a look at below program.

Example:-

>>>name= ‘Tannavi’

>>>print(name[2:10])

Output : nnavi

As we can see that in this program we have taken the ending index to be 10 which is not present in the string. On encountering such cases the end index is automatically taken to be the last index.


If we need to skip a certain number of steps then we simply specify it after the last index using the slicing operator.

  • By default, it is 1.

Example:-

>>>name= ‘Tannavi’

>>>print(name[-5:-1])

OUTPUT: nnav 


Syntax for Slice Operator

variable name[starting index : last index : step increment]

Example Program :-

>>>name= ‘Tannavi’

>>>print(name[0:10:2])

OUTPUT: Tnai

Here, we take the step increment to be 2 along with the slice operator so that we get two-step increment after every character.

  • Python provides a lot of flexibility in manipulating strings. For instance, if we want to display a string multiple times we just write the following code.

Example:-

>>>m= “meow”

>>>m*4

>>>len(mew)

Output : –
‘meowmeowmeowmeow’
4

Here, we take the string literal ‘m’ and use the ‘*’ operand followed by the number of times that the string needs to be printed consecutively.

  • A similar program in another language might require multiple lines of code.
  • To find the length we use the predefined function len().
  • There are five data types that constitute the Python’s Fundamental data types.
  • To declare single characters we use the string data type only and there is no explicit char data type.

Type Casting or Type Coercion in Python

There are a few type conversion functions present in Python which help us to accomplish this task.

Namely, 

  1. int()
  2. float()
  3. complex()
  4. bool()
  5. str()
  • Float to int :- This conversion can be done by simply using the int() function.

Example:  >>>int(657.123)
Output :  657

  • Complex to int :- Converting from complex data type is not possible and so it shows a type error on trying to do so.
  • Boolean to int :- It is possible to convert boolean values to integral form as True and False represent 1 and 0 respectively.

Example: >>>int(True)
 Output : 1

Example: >>>int(False)
 Output : 0

  • String to int :- String values are always stored in integer values so it is possible to convert easily.

Note: The value must always be in base 10 to be converted.

Example: >>>float(“657”)
 Output : 657

  • Int to Float :- This conversion can be done by simply using the int() function.

Example: >>>float(657)
Output : 657.0

  • Complex to float :- Converting from complex data type to float is not possible and so it shows a type error on trying to do so.
  • Boolean to float :- It is possible to convert as True and False represent 1 and 0 respectively.

Example: >>>float(True)
Output : 1.0

Example : >>>float(False)
Output  : 0.0

  • String to float :- String values are always stored in numerical values so it is possible to convert easily.

Note: The value must always be an integral value or floating point value in base 10 to be converted.

Example: >>>float(“657”)
Output : 657.0

Example : >>>float(“six”)
Output : ValueError: could not convert string to float

This is all about the slice operator in python.

Leave a Comment

Your email address will not be published. Required fields are marked *