How to Get Substring from a String in Python using string slicing


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
>>> 
Substring from a String in Python using string slicing Examples

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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap