Doing slicing will extract part of a string in Python. Use square-bracket syntax with the starting position of the piece we want, but also where it ends.
string[start: end: step]
- start: The starting index of the extracing part. Default value is 0.
- end: The terminating index of the substring.
- step: Every ‘step’ character after the current character to be included. The default value is 1.
Python extract part of a string example
Simple example code.
Extract characters of a string
string = "Hello Python developer" print(string[0:7])
Extract the substring of length 4 from the 3rd character of the string
string = "Python developer" print(string[2:6])
Get every other character from a string
string = "Hello Python developer" print(string[::2])
Output: HloPto eeoe
Do comment if you have any doubts and suggestions on this Python string topic.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.