Python : Finding first and last n characters of a string

Python supports positive and negative indexes for accessing array elements.

  • Positive indexes start from the beginning of the array. The first positive index is 0.
  • Negative indexes start from the end of the array and begin with -1.
  • A sub-array can be found using [ begin : end ] notation.
    Note : index begin is always smaller than index end.
    Example : text [ 0 : 4 ] will return a text with the first 4 characters from 0 to 3
    ( not including the character at index 4 ).
    • If begin is not specified, it is considered index 0 i.e the beginning of the array.
      Example : text [ : 3 ] will return a text from beginning till index 2.
    • If end is not specified, it is considered the end of the array i.e last index.
      Example : text [ 2 : ] will return a text from index 2 till end.

First_And_Last_N_Characters


















Python program for finding the first and last N characters of a string.

text = "Winter is coming"

first_4 = text [ 0 : 4 ]
first_3 = text [ : 3 ]
last_8  = text [ -8 : ]
last_1  = text [ -1 ]
from_beginning_to_minus_6 = text [ : -6 ]
from_minus_6_to_minus_3 = text [ -6 : -3 ]
from_minus_6_to_minus_5 = text [ -6 : -5 ]

print("First 4 characters : " + first_4)
print("First 3 characters : " + first_3)
print("Last 8 characters : " + last_8)
print("Last character : " + last_1)
print("From beginning to -6 : " + from_beginning_to_minus_6)
print("In range -6 to -3 : " + from_minus_6_to_minus_3)
print("In range -6 to -5 : " + from_minus_6_to_minus_5)

Output

First 4 characters : Wint
First 3 characters : Win
Last 8 characters : s coming
Last character : g
From beginning to -6 : Winter is 
In range -6 to -3 : com
In range -6 to -5 : c


Copyright (c) 2019-2023, Algotree.org.
All rights reserved.