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:
Format ZonedDateTime to String
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python String startswith()
Generate a String
Python object()
Python round()
Python Program to Compute the Power of a Number
Python Set difference()
Python Dictionary pop()
Python Global, Local and Nonlocal variables
Python Program to Get Line Count of a File
Java – Reader to String
Python Program to Create Pyramid Patterns
Python String rfind()
Python Set isdisjoint()
Python Program to Display Fibonacci Sequence Using Recursion
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Access Index of a List Using for Loop
JavaScript Eval: run a code string
Python Program to Extract Extension From the File Name
Python Program to Append to a File
Case-Insensitive String Matching in Java
Python Program to Find the Sum of Natural Numbers
Python Program to Multiply Two Matrices
Python Program to Find HCF or GCD
Python compile()
Python String replace()
Python Program to Check the File Size
Python String isalnum()
Python frozenset()
Python Program to Merge Mails
Python Program to Swap Two Variables