Change language

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

| |

# 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

Output:

Traceback (last call was last): File 8a33ebbf716678c881331d75e0b85fe6.py, line 15, in "module" print x [15] IndexError: string index out of range
 f o 

slicing

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.

Example-

# 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

Output:

 LCO TON Ge 

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

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method