Python substring

Ways to slice the Python’s substring

There are many ways in Python to use a string as a substring. This is often referred to as “slicing”. But if you are puzzled about the ways to do it, we are here to help you. The syntax is as follows:

string [start: end: step]

Start location: Substring start index. The characters in this index are contained in the substring. If start is not included, it is assumed to be 0.

end: The final index of the substring. The characters in this index are not in the substring. If the end is not included or the specified value exceeds the length of the string, it is assumed to be the length of the string by default.

Step: Each “step” character after the current character is to be inserted. The default is 1. If no step is included, it is considered equal to 1.

 Basic use

string [start: end]: Get all characters from the beginning(Start) to the end 1

string [: end]: Get all the characters from the beginning(Start) to the end 1

string [start:]: Get all the characters from the beginning(Start) of the string Get all characters to the end

string [start: end: step]: Get all characters from start to finish(end) without step characters

You will understand it in a better manner with the help of examples.

Examples

  1. Get the first 5 characters of the string

string = “freeCodeCamp

Print (character string [0: 5])

Output:

> freeC

Note: print (string [: 5]) provides the same result as a print (string [0: 5]).

  1. Gets a 4 character long Python’s substring starting with the 3rd character of the string

string = “freeCodeCamp

Print (character string [2: 6])

Edition:

> eeCo

  1. Get the last character in the string

string = “freeCodeCamp

Print (character string [-1])

Edition:

> p

Note that the start or end index can be negative. A negative index means that the count starts at the end of the string, not at the beginning of the string (right to left).

Index 1 represents the last character in the string and 2 represents the penultimate character.

  1. Get the last 5 characters of the string

string = “freeCodeCamp

Print (character string [5:])

Edition:

> eCamp

  1. Get a substring containing all but the last 4 characters and the first character

string = “freeCodeCamp

Print (character string [1: 4])

Output:

> reeCode

  1. Get every other character from a string

string = “freeCodeCamp

Print (character string [:: 2])

Output:

> feCdCm

We hope that you can do so without any confusion and ease.

Leave a Reply