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:
Adding a Newline Character to a String in Java
Python Program to Find Sum of Natural Numbers Using Recursion
Python Set difference()
Python compile()
Python classmethod()
String Hashing
Python ord()
Count Occurrences of a Char in a String
Python Program to Compute the Power of a Number
Python Object Oriented Programming
Python Program to Sort Words in Alphabetic Order
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Calculate the Area of a Triangle
Python complex()
Python Program to Iterate Through Two Lists in Parallel
Python Program to Convert String to Datetime
Python String expandtabs()
Python Dictionary update()
Python Program to Concatenate Two Lists
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python abs()
Python Program to Trim Whitespace From a String
Python all()
Python String isnumeric()
Python Program to Display Fibonacci Sequence Using Recursion
Python sleep()
Python String split()
Python Tuple count()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Reading an HTTP Response Body as a String in Java
Python String istitle()
Python Numbers, Type Conversion and Mathematics