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 bytes()
Python Dictionary pop()
Python String lstrip()
Python Functions
Python Program to Find LCM
Python String isupper()
Python Anonymous / Lambda Function
Python frozenset()
Python classmethod()
Python String swapcase()
Python Program to Append to a File
Python List clear()
Python staticmethod()
Python Program to Differentiate Between del, remove, and pop on a List
How to Get Started With Python?
Python File I/O Operation
JavaScript Eval: run a code string
Python Program to Find All File with .txt Extension Present Inside a Directory
Python bool()
Python String rstrip()
Python Sets
Python Variables, Constants and Literals
Python Program to Check If Two Strings are Anagram
Python String splitlines()
Python if...else Statement
Java – String to Reader
Python String islower()
Python Numbers, Type Conversion and Mathematics
Python Program to Delete an Element From a Dictionary
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Program to Count the Number of Each Vowel
Python Get Current time