Computer >> Computer tutorials >  >> Programming >> Python

How can we get substring from a string in Python?


In Python, string data type is an ordered sequence of characters. All sequence data types support slicing. Using the slice operator “:”, a substring can be obtained from main string. 

Example

>>> string="Hello How are you?"
>>> string[6:9]
'How'

The slice operator − requires two operands. First operand is the index of first character of desired substring. The resultant substring contains main string’s characters at indices upto but not including second operand. In above example, characters at index 6 to 8 will form the substring. (Index count starts from 0)