Skip to content

String slicing in Python | Example code

  • by

Getting a substring from a given string is called String slicing in Python. A simple way to do this is to use the simple slicing operator.

Python string slicing can be done in two ways.

  • slice() Constructor
  • Extending Indexing

Example String slicing in Python

A simple example code demonstrates string slicing.

Using slice() Constructor

Use slice notation (start, stop, step).

String = 'HELLO'

# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)

print(String[s1])
print(String[s2])
print(String[s3])

Output:

String slicing in Python

Extending indexing

string[start:end:step]

start end and step have the same mechanism as the slice() constructor.

String = 'HELLO'

print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])

Output:

HEL
EL
OLH

Slice From the Start

Don’t use the start index, the range will start at the first character. Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

Output: Hello

Slice To the End

Don’t use the end index, the range will go to the end. Get the characters from position 6, and all the way to the end:

b = "Hello, World!"
print(b[6:])

Output: World!

Do comment if you have any doubts or suggestions on this Python slicing 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading