String Slicing in Python
String in Python is stored as an array so array indexing can be used to access
characters of a String, for example str[0] returns first character of the String str.
You may have a scenario where you want to access a part of String rather than a
single character, in that case you can use string slicing using slice operator in
Python.
Python string slicing
Format of String slicing is as follows-
Stringname[start_position: end_position: increment_step]
start_position is the index from which the string slicing starts,
start_position is included.
end_position is the index at which the string slicing ends, end_position is
excluded.
increment_step indicates the step size. For example if step is given as 2
then every alternate character from start_position is accessed.
All of these parameters are optional, if start_position is not specified then the
slicing starts from index 0. If end_position is not specified then the slicing ends at
string_length – 1 (last index). If increment_step is not specified then increment
step is 1 by default.
Python string slicing examples
1- A simple example where substring from index 2..3 is required.
s = "Python String Slicing"
print(s[2: 4: 1])
Output
th
Here slicing is done from index 2 (start_pos) to index 3 (end_pos-1). Step size is 1.
2- If no parameters are specified.
s = "Python String Slicing"
#both are valid
print(s[:])
print(s[: :])
Output
Python String Slicing
Python String Slicing
3- String slicing when step size is greater than one.
s = "Python String Slicing"
print(s[3: 8 : 2])
Output
hnS
Since the step size is 2 so every other character with in the limits of start_pos and
end_pos is accessed.
4- Using string slicing in conjunction with other Python string methods. For example
if there is a data in dd/mm/yyyy format and you want to access only the month
part. In this case you can use index method to specify the start and end positions
for slicing.
s = "03/05/2019"
print(s[s.index("/")+1: s.rindex("/") : 1])
Output
05
String slicing with negative indexing
In string in Python you can also use negative indexing. When negative number is
used as index String is accessed backward so -1 refers to the last character, -2
second last and so on.
1- Reversing the string using slicing. By providing increment_step as -1 you can
reverse a string.
s = "Hello World"
reversed = s[: :-1]
print(reversed)
Output
dlroW olleH
2- Using negative value as start position and step size is +1.
s = "Hello World"
str = s[-5: :]
print(str)
Output
World
Here step size is +1 so the indices that are accessed are -5, -4, -3, -2, -1
That's all for this topic String Slicing in Python. If you have any doubt or any
suggestions to make please drop a comment