Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Create a string made of the first and last two characters from a given string
This tutorial demonstrates how to create a new string using the first and last two characters from a given string through string slicing. This technique is useful for data processing, text formatting, and extracting key information from strings.
Algorithm
Start with the given string
Use slicing
[:2]to extract the first two charactersUse negative slicing
[-2:]to extract the last two charactersConcatenate both parts to form the new string
Basic Example
Here's the simple approach to create a new string from first and last two characters ?
given_string = "TechCrunch"
new_string = given_string[:2] + given_string[-2:]
print("Original:", given_string)
print("New String:", new_string)
Original: TechCrunch New String: Tech
More Examples
Let's see how this works with different strings ?
# Example 1
string1 = "Python"
result1 = string1[:2] + string1[-2:]
print(f"'{string1}' becomes '{result1}'")
# Example 2
string2 = "FastAPI"
result2 = string2[:2] + string2[-2:]
print(f"'{string2}' becomes '{result2}'")
# Example 3
string3 = "Programming"
result3 = string3[:2] + string3[-2:]
print(f"'{string3}' becomes '{result3}'")
'Python' becomes 'Pyon' 'FastAPI' becomes 'FaPI' 'Programming' becomes 'Prng'
Understanding String Slicing
String slicing uses square bracket notation with start and end indices separated by a colon ?
text = "Hello, Python!"
# Basic slicing
print("Characters 2-7:", text[2:7])
# First two characters
print("First two:", text[:2])
# Last two characters
print("Last two:", text[-2:])
# Reverse string
print("Reversed:", text[::-1])
Characters 2-7: llo, First two: He Last two: n! Reversed: !nohtyP ,olleH
Step-by-Step Breakdown
# Given string
original = "FastAPI"
# Step 1: Extract first two characters
first_two = original[:2]
print("First two characters:", first_two)
# Step 2: Extract last two characters
last_two = original[-2:]
print("Last two characters:", last_two)
# Step 3: Combine them
result = first_two + last_two
print("Combined result:", result)
First two characters: Fa Last two characters: PI Combined result: FaPI
Function Implementation
You can create a reusable function for this operation ?
def first_last_two(string):
"""Create new string from first and last two characters"""
if len(string) < 4:
return string # Return original if too short
return string[:2] + string[-2:]
# Test the function
test_strings = ["Python", "AI", "Programming", "Code"]
for text in test_strings:
result = first_last_two(text)
print(f"'{text}' ? '{result}'")
'Python' ? 'Pyon' 'AI' ? 'AI' 'Programming' ? 'Prng' 'Code' ? 'Code'
Common Use Cases
| Application | Description | Example |
|---|---|---|
| Data Processing | Extract key identifiers | Username abbreviations |
| Text Formatting | Create compact displays | Short labels for UI |
| File Processing | Generate quick references | File name shortcuts |
Conclusion
String slicing with [:2] and [-2:] provides an efficient way to extract first and last characters. This technique is valuable for text processing, data manipulation, and creating abbreviated forms of strings in Python applications.
