Friday, February 14, 2020

Getting Substring in Python String

In this post we’ll see how to get a substring from a string in Python. Driven by habit most of the developers look for a method in the str class for getting a substring but in Python there is no such method. Getting a substring from a string is done through String slicing in Python.

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.

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. In this case you can use find method to specify the start and end positions for getting a substring.

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

  1. Accessing Characters in Python String
  2. Python count() method - Counting Substrings
  3. Comparing Two Strings in Python
  4. Convert String to int in Python
  5. Functions in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. self in Python
  3. Polymorphism in Python
  4. Python while Loop With Examples
  5. Zipping Files And Folders in Java
  6. Java Collections Interview Questions And Answers
  7. Spring Object XML Mapping (OXM) JAXB Example
  8. How to Create Ubuntu Bootable USB