Multiple ways to get Substring of a string in Python|Slicing example
This tutorial explains how to find substrings or slices of a given string.
For example, if the string contains “hello,” possible substrings include individual characters like ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, or the entire word ‘hello.‘
Substring or slicing involves extracting a part of the main string based on given start and end indices.
Let’s understand how strings are stored with index
+---+---+---+---+---+---+
| h | e | l | l | o | w |
+---+---+---+---+---+---+
Start (Positive): 0 1 2 3 4 5
End (positive) : 5 4 3 2 1 0
String slice in Python example
- Using string[start:end] Syntax
Substrings are calculated using the string[start:end]
syntax.
string[start:end]
start and end are the starting and ending indices, returning characters between these indices. The result is a string with characters from start to end-1.
If values are positive, the indices are iterable in the forward direction. For example, in the string hello
, start=0
corresponds to h
, and end=4
(length-1) corresponds to o
.
If values are negative, the indices are iterable in the reverse direction. For example, in the string hello
, start=-1
corresponds to o
, and end=-4
(-length-1) corresponds to h
.
Here is an example
str="hello welcome"
print(str[1:]) # ello welcome
print(str[:1]) # h
print(str[-1:]) # e
print(str[:-1]) # hello welcom
print(str[1:-1]) # ello welcom
print(str[:]) # hello welcome
str[1:]
: Start index is 1, and the end index is unknown (until the end of the string). str[:1]
: Start is unknown (beginning of the string), and the end is 1. str[-1:]
: Start index is the second character from the end of the string, and the end is the beginning in reverse direction. str[:-1]
: Start is unknown, and the end is -1 (second character from the end of the string). str[1:-1]
: Start is 2 characters from the beginning, and the end is -1 (second character from the end). str[:]
: Returns the complete string.
- Using string[start:end:step]
Another syntax involves using a step
value.
string[start:end:step]
start
: Start index of a string, includes the character in the substring. Default is 0.end
: End index of a string, does not include the character in the substring. Default is length - 1.step
: Amount of index increase. Default is 1. For negative values, the substring is iterable in the reverse direction.
Here is an example
str="hello welcome"
print(str[1::])# ello welcome
print(str[::1])# hello welcome
print(str[1:2:4]) # e
print(str[-1:None:None]) #e
print(str[1:None:-1]) #eh
print(str[:-1:None]) # hello welcom
This tutorial covers various approaches for finding substrings in Python strings using different approaches.