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:
Python Program to Find Hash of File
Python Variables, Constants and Literals
Python range()
Python Exception Handling Using try, except and finally statement
Python Machine Learning - Sebastian Raschka
Node.js vs Python for Backend Development
Python Program to Return Multiple Values From a Function
Python String format_map()
Python Program to Convert Bytes to a String
Python sorted()
Python String capitalize()
Python classmethod()
Python List count()
Python Set intersection_update()
Python List pop()
Python String strip()
Python List index()
Python id()
Python Program Read a File Line by Line Into a List
Python Dictionary clear()
Python Global, Local and Nonlocal variables
Python __import__()
Python Program to Make a Simple Calculator
Python Set difference_update()
Python Set add()
Python Data Types
Python String zfill()
Java – String to Reader
Python Program to Convert Two Lists Into a Dictionary
Python Program to Check If Two Strings are Anagram
Python all()
Python Program to Convert Celsius To Fahrenheit