Getting a substring from a given string is called a String slicing in Python. A simple way to do this is to use the simple slicing operator.
Python string slicing can be done in two ways.
- slice() Constructor
- Extending Indexing
Example String slicing in Python
Simple example code demonstrates string slicing.
Using slice() Constructor
Use slice notation (start, stop, step).
String = 'HELLO' # Using slice constructor s1 = slice(3) s2 = slice(1, 5, 2) s3 = slice(-1, -12, -2) print(String[s1]) print(String[s2]) print(String[s3])
start end and step have the same mechanism as slice() constructor.
String = 'HELLO' print(String[:3]) print(String[1:5:2]) print(String[-1:-12:-2])
Slice From the Start
Don’t use the start index, the range will start at the first character. Get the characters from the start to position 5 (not included):
b = "Hello, World!" print(b[:5])
Slice To the End
Don’t use the end index, the range will go to the end. Get the characters from position 6, and all the way to the end:
b = "Hello, World!" print(b[6:])
Do comment if you have any doubts and suggestions on this Python slicing topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.