Python Program to Extract First and Last Two Characters of a String
Last updated 3 months ago | 164 views 75 5

When working with strings in Python, there are times when you need to extract specific parts of a given string. In this tutorial, we will write a simple Python program that extracts the first two and last two characters of a string. If the string length is less than 2, the program will return an empty string.
Python Solution
The program follows these simple steps:
✅ Check if the length of the string is less than 2. If yes, return an empty string.
✅ Otherwise, extract the first two and last two characters using string slicing.
✅ Concatenate them and return the final result.
Python Code Implementation
def first_last_chars(s):
if len(s) < 2:
return "" # Return an empty string if the length is less than 2
return s[:2] + s[-2:] # Extract first 2 and last 2 characters
# Example usage
print(first_last_chars("Python")) # Output: Pyon
print(first_last_chars("Hi")) # Output: HiHi
print(first_last_chars("A")) # Output: (empty string)
print(first_last_chars("")) # Output: (empty string)
Explanation
- Case 1: "Python" → First two: "Py", Last two: "on" → Result: "Pyon"
- Case 2: "Hi" → First two: "Hi", Last two: "Hi" → Result: "HiHi"
- Case 3: "A" → Length is less than 2, so returns an empty string
- Case 4: "" (empty string) → Returns an empty string
Why Use This Approach?
✅ Simple and efficient: Uses basic string slicing.
✅ Handles all cases: Works for any string length, including empty strings.
✅ Beginner-friendly: Easy to understand and implement.
This small yet useful string manipulation trick can be helpful in text processing applications, form validation, and more. Try it out and enhance your Python skills!