When it comes to getting substring in Python string, many developers instinctively look for a built-in substring() method, as found in other languages. However, Python takes a different approach, there is no dedicated method for substrings. Instead, Python uses the powerful concept of string slicing, which is both flexible and concise.
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 three parameters are optional-
- If start_position is omitted, slicing starts from index 0.
- If end_position is omitted, slicing continues to the last character.
- If step is omitted, the default is 1.
Getting substring through Python string slicing examples
1. A simple example where substring from index 2..3 is required.
s = "Test String" print(s[2: 4: 1])
st
Here slicing is done from index 2 (start_pos) to index 3 (end_pos-1). Step size is 1.
2. Access only the month part from a date in dd/mm/yyyy format. Python makes this simple using string slicing combined with the find() method.
s = "18/07/2019"
month = s[s.find("/")+1: s.rfind("/") : 1]
print('Month part of the date is-', month)
Month part of the date is- 07
That's all for this topic Getting Substring in Python String. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-