In this article, we will learn about slicing string in python.
Getting Started
Slicing string allows developers to get substring as per provided range of indexes.
Syntax of String Slicing –
str[start:stop:step]
Here,
- str: Python String to be sliced
- start: First index of range
- stop: Last index of range
- step: Number of step from any index i to next index.
For example,
s[i:j:k]
In above code, we slice string s from i to j with step k.
Examples: String Slicing in Python
-
str[0:4] Returns elements from 0th index to 4th index(excluded) i.e. from 0th to 3rd index (0, 1, 2, 3 position). For example,
str="Hardeo" print(str[0:4]) #output- Hard
Output:
Hard
In above code,
H: present at 0th index
a: present at 1st index
r: present at 2nd index
d: present at 3rd index - str[0:6:2] Returns elements from 0th index to 6th index(Excluded) in steps of 2 i.e. elements from alternate index will be returned starting from 0th index. For example,
str="Hardeo" print(str[0:6:2]) # output- Hre
Output:
Hre
In above code,
H: present at 0th index
r: present at 2nd index
e: present at 4th index
str[::] Returns elements from 0th index till end of the string. If any value is omitted, it has default values –
If first index is omitted, default value is 0.
If 2nd index is omitted, default value is length of the string being sliced.
If last index is omitted, default value is 1.For example,
str="Hardeo" print(str[::]) # output- HardeoOutput:
Hardeo
Omitted Index
- str[:2] Returns elements of string from First index to 2nd index (excluded) . For example,
str="Hardeo" print(str[:2]) # output- Ha
Output:
HaIn above code,
H – present at 0th index
a – present at 1st index - str[2:] returns elements of string from 2nd index till last character of string. For example,
str="Hardeo" print(str[2:]) # output- rdeo
Output:
rdeo
Negative Index
Negative indexing can also be used for string slicing in python. It means counting will start from end of the string till first character of string.
- str[:-2] returns elements from first element till 2nd last element of string (exlcuded). For example,
str="Hardeo" print(str[:-2]) # output- Hard
Output:
Hard
- str[-2:] returns elements from 2nd last element till end of string. For example,
str="Hardeo" print(str[-2:]) # output- eo
Output:
eo - str[::-2] returns elements from end till start in reverse order in steps of 2. For example,
str="Hardeo" print(str[::-2])#output-oda (reverse 2 stepover)
Output:
oda
- str[::-1] returns elements from end till start in reverse order in steps of 1. For example,
str="Hardeo" print(str[::-1]) #reverse
Output:
oedraH
Here, we have reversed the string using slicing in python.
Out of Range Index
- Slicing in python handles out of range gracefully. For example,
str="Hardeo" print(str[19:])
Output:
# No Output
That’s how we can use slice a string in python using indexing, negative indexing etc.
Reference: Official Doc
You must be logged in to post a comment.