Python Program to Create a New String Made up of First and Last 2 Characters

This is a Python Program to form a new string made of the first 2 characters and last 2 characters from a given string.

Problem Description

The program takes a string and forms a new string made of the first 2 characters and last 2 characters from a given string.

Problem Solution

1. Take a string from the user and store it in a variable.
2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string and increment the count variable each time.
4. Form the new string using string slicing.
5. Print the newly formed string.
6. Exit.

Program/Source Code

Here is source code of the Python Program to form a new string made of the first 2 characters and last 2 characters from a given string. The program output is also shown below.

string=raw_input("Enter string:")
count=0
for i in string:
      count=count+1
new=string[0:2]+string[count-2:count]
print("Newly formed string is:")
print(new)
Program Explanation

1. User must enter a string and store it in a variable.
2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. The count is incremented each time a character is encountered.
5. The new string is formed by using string slicing and the first two letters and the last two letters of the string are concatenated using the ‘+’ operator.
6. The newly formed string is printed.

advertisement
Runtime Test Cases
 
Case 1:
Enter string:Hello world
Newly formed string is:
Held
 
Case 2:
Enter string:Checking
Newly formed string is:
Chng

Sanfoundry Global Education & Learning Series – 1000 Python Programs.

If you wish to look at all Python Programming examples, go to 1000 Python Programs.

🎓 Register Today for Free C++ Certification - January 2026

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels

advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations