/  Technology   /  How do I get a substring of a string in Python?
How do I get a substring of a string in Python

How do I get a substring of a string in Python?

 

There is no inbuilt method in Python like other languages to get a substring of a string. We use the concept of slicing here. Slicing helps in obtaining a substring, sub-tuple, or sublist from any given iterable like a string, tuple, or list respectively.

 

Syntax of slicing :

[start_at : stop_before: step]
  • start_at is the index of the first item to be returned (included).
  • stop_before is the index of the element before which the iteration stops (not included).
  • step is the stride or the jump between any two items.

Note: All three of the arguments are optional which means you can skip using any of them.

  • string [start_at: stop_before]   items start from start_at and end at stop_before
  • string  [start_at:]   items start from start_at print  the rest of the array
  • string [: stop_at]   items start from the beginning and end at stop_before
  • string [:]      a copy of the whole sequence

 

Example:

string = "Python by i2tutorials"

print("Original String is: ", string)

sub_string = string[:7]
print("Substring:", sub_string)

sub_string = string[7:]
print("Substring:", sub_string)

sub_string = string[7:9]
print("Substring:", sub_string)

sub_string = string[:-1]
print("Substring:", sub_string)

sub_string = string[1:21:2]
print("Substring:", sub_string)

Output:

 

The second approach of getting substrings of a list is by creating a slice object using the slice(). It takes in three indices similar to regular slicing i.e., start, stop, step separated by commas and enclosed in parentheses. 

slice(start, stop, step)

We print the sublist by

original_string[slice_object]

 

Example:

string = "Python by i2tutorials"
print("Original String is: ", string)

slice_obj = slice(7,9,1)

print("Substring:", string[slice_obj])

Output:

Leave a comment