Python extract part of a string | Example code

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])

Output:

Python extract part of a string

Extract the substring of length 4 from the 3rd character of the string

string = "Python developer"
print(string[2:6])

Output: thon

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.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.