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
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 – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.