In this example, you will learn to get a substring of a string.
To understand this example, you should have the knowledge of the following Python programming topics:
Using String slicing
my_string = "I love python." # prints "love" print(my_string[2:6]) # prints "love python." print(my_string[2:]) # prints "I love python" print(my_string[:-1])
Output
love love python. I love python
String slicing works similar to list slicing. The working of above code can be understood in the following points.
[2:6]
You need to specify the starting index and the ending index of the substring. In this case,love
starts at index 2 and ends at index 6.[2:]
All the text from index 2 to the end are selected.[:-1]
All the text before the last index is selected.
Related posts:
Deep Learning with Python - Francois Cholletf
Count Occurrences of a Char in a String
Python Custom Exceptions
Python hasattr()
Python Modules
Python Objects and Classes
Python print()
Converting a Stack Trace to a String in Java
Python List append()
Python Tuple
Python Program to Check If Two Strings are Anagram
Python Program to Merge Two Dictionaries
Case-Insensitive String Matching in Java
Python String find()
Python String strip()
Python Multiple Inheritance
Python Program to Count the Occurrence of an Item in a List
Python Package
Python Set difference_update()
Python next()
Python Program to Count the Number of Each Vowel
Python List sort()
Python slice()
Python Directory and Files Management
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Set isdisjoint()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Set discard()
Python del Statement
Python List remove()
String Set Queries
Python List copy()