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,lovestarts 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:
Python List sort()
Python String endswith()
Python String rfind()
Convert String to Byte Array and Reverse in Java
Python Program to Get the Full Path of the Current Working Directory
Python List index()
Convert String to int or Integer in Java
Python frozenset()
Python dir()
Python Exception Handling Using try, except and finally statement
Python tuple()
Python sorted()
Python complex()
Python String center()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python getattr()
Python Program to Represent enum
Python while Loop
Python set()
Python String format_map()
Python Program to Compute the Power of a Number
Python sleep()
Python Program to Find HCF or GCD
Python List remove()
Most commonly used String methods in Java
Python Program to Catch Multiple Exceptions in One Line
Python Program to Find Factorial of Number Using Recursion
Python Dictionary keys()
Python Package
Python Program to Display Powers of 2 Using Anonymous Function
Check If a String Is Numeric in Java
Python Input, Output and Import