Skip to content

Python extract part of a string | Example code

  • by

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

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *