We can make use of string slicing to get the substring from a string in Python.
Syntax:
string[start:end:step]
- start: Indicates the beginning of a string. default: 0
- end: indicates the endo fo the string. default: length of the string
- step: indicates consecutive elements. default: 1
Let's say we have a string "I am learning Python" and we want to get the strings at the first and last index in this sentence as a substring.
>>> sentence = "I am learning Python"
>>> first_word = sentence[:sentence.index(' ')]
>>> print(first_word)
I
>>>
>>> last_word = sentence[sentence.rindex(' ') + 1:]
>>> print(last_word)
Python
>>>

More Examples:
>>> string = "I Love Python"
>>>
>>> substring1 = string[2:6]
>>> print(substring1)
Love
>>>
>>> substring2 = string[2:]
>>> print(substring2)
Love Python
>>>
>>>
>>> substring3 = string[:6]
>>> print(substring3)
I Love
>>>
>>> substring4 = string[::2]
>>> print(substring4)
ILv yhn
>>>
>>> substring5 = string[::-1]
>>> print(substring5)
nohtyP evoL I
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!