EN
Python - get substring of string
0 points
In this article, we would like to show you how to get a substring of the string in Python.
Quick solution:
xxxxxxxxxx
1
text = "dirask is cool"
2
substring = text[0:7] # start from index 0 up to 7
3
print(substring) # dirask
In this example, we use slicing to get a substring from the text
.
xxxxxxxxxx
1
text = "dirask is cool"
2
3
substring1 = text[0:7] # dirask (start from index 0 to 7)
4
substring2 = text[:7] # dirask (from index 0 by default to index 7)
5
substring3 = text[-14:-7] # dirask (counting from the end of the string)
6
7
substring4 = text[7:9] # is (positive indexing)
8
substring5 = text[-7:-4] # is (negative indexing)
9
10
substring6 = text[10:14] # cool
11
substring7 = text[10:] # cool (from index 10 to the end of the string)
12
substring8 = text[-4:] # cool (from index -4 to the end of the string)
13
substring9 = text[-4:14] # cool
14
15
16
print(substring1) # dirask
17
print(substring2) # dirask
18
print(substring3) # dirask
19
20
print(substring4) # is
21
print(substring5) # is
22
23
print(substring6) # cool
24
print(substring7) # cool
25
print(substring8) # cool
26
print(substring9) # cool
Output:
xxxxxxxxxx
1
dirask
2
dirask
3
dirask
4
is
5
is
6
cool
7
cool
8
cool
9
cool