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:
text = "dirask is cool"
substring = text[0:7] # start from index 0 up to 7
print(substring) # dirask
Practical example
In this example, we use slicing to get a substring from the text
.
text = "dirask is cool"
substring1 = text[0:7] # dirask (start from index 0 to 7)
substring2 = text[:7] # dirask (from index 0 by default to index 7)
substring3 = text[-14:-7] # dirask (counting from the end of the string)
substring4 = text[7:9] # is (positive indexing)
substring5 = text[-7:-4] # is (negative indexing)
substring6 = text[10:14] # cool
substring7 = text[10:] # cool (from index 10 to the end of the string)
substring8 = text[-4:] # cool (from index -4 to the end of the string)
substring9 = text[-4:14] # cool
print(substring1) # dirask
print(substring2) # dirask
print(substring3) # dirask
print(substring4) # is
print(substring5) # is
print(substring6) # cool
print(substring7) # cool
print(substring8) # cool
print(substring9) # cool
Output:
dirask
dirask
dirask
is
is
cool
cool
cool
cool