Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String

When it is required to form a new string that is made from the first two and last two characters of a given string, a counter can be defined, and indexing can be used to access specific range of elements.

Below is the demonstration of the same −


 Live Demo

my_string = "Hi there how are you"

my_counter = 0

for i in my_string:
   my_counter = my_counter + 1
new_string = my_string[0:2] + my_string [my_counter - 2: my_counter ]

print("The string is ")
print("The new string is ")


The string is
Hi there how are you
The new string is


  • A string is defined and is displayed on the console.

  • A counter is initiated to 0.

  • The string is iterated over, and the first 2 and last two elements are accessed using indexing.

  • This is assigned to a variable.

  • It is the output that is displayed on the console.