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 −
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(my_string) print("The new string is ") print(new_string)
The string is Hi there how are you The new string is Hiou
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.