/  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.

 

The syntax of slicing is [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

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].

Leave a comment