Fun Facts About Strings in Python | Set 2 (slicing)

File handling | Python Methods and Functions | String Variables

# Python program to illustrate slicing in lines


x = "Geeks at work"

# Prints the third character, starting with 0

print x [ 2

# Prints the 7th character

print x [ 6

# Prints the third character from the back, starting at -1

print x [ - 3

# Line length is 10, so it is out of bounds

print x [ 15


Traceback (last call was last): File, line 15, in & lt; module & gt; print x [15] IndexError: string index out of range
 f o 


To extract a substring from an entire string, we use the following syntax

  string_name [start: end: step]   
  • start represents the starting index of the line
  • the end indicates the ending index of a line that is not inclusive
  • steps indicate the distance between two words.

Note: we can also slice a line using the beginning and only , and steps are optional.


# Program in Python for illustration # print substrings of the string

x = "Welcome to GeeksforGeeks"

# Prints a substring from the 2nd to the 5th character

print x [ 2 : 5

# Prints 2nd character substring
# 4th to 10th character

print x [ 4 : 10 : 2

# Pe chat 3rd character from behind from 3 to 5

print x [ - 5 : - 3



This article courtesy of Arpit Agarwal. If you like Python.Engineering and you want to contribute, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic under discussion

Get Solution for free from DataCamp guru