Python Program to Get a Substring of a String – 2024

Hey guys, in this blog we will see a Python Program to Get a Substring of a String.

Using String slicing

my_string = "I love blogs from Machine Learning Projects."

# prints "I love blogs"
print(my_string[:12])

# prints "Machine Learning Projects"
print(my_string[18:-1])

# prints "Machine Learning Projects"
print(my_string[18:-10])

# prints "love blogs from Machine Learning Projects."
print(my_string[2:])

# prints "I love blogs from Machine Learning Projects"
print(my_string[:-1])

Output

I love blogs
Machine Learning Projects
Machine Learning
love blogs from Machine Learning Projects.
I love blogs from Machine Learning Projects
  • While slicing a string, keep one thing in mind every character is given an index. For eg on index 0 ‘I’ s present, on index 1 a space character is present, and so on…
  • In the first example, we have printed my_string[:12] which says to print every character from my_string starting from the start to the 12th character (excluding the 12th character).
  • In the second example, we have printed my_string[18:-1] which says to print every character from my_string starting from the 18th character to the last character (excluding the last character which is a full stop).

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 514

Leave a Reply

Your email address will not be published. Required fields are marked *