Python Practice › String Programs › Program 1
First and last 2 characters
Write a Python program to build a string from the first 2 and the last 2 characters of a string. If the string is shorter than 2 characters, return an empty string.
Input
"Sqatools", "Py", "S"
Output
'Sqatools' -> 'Sqls' 'Py' -> 'PyPy' 'S' -> ''
Approach
- Check the length first; then join two slices.
Solution
def ends(text): if len(text) < 2: return "" return text[:2] + text[-2:] for t in ["Sqatools", "Py", "S"]: print(repr(t), "->", repr(ends(t)))Output
'Sqatools' -> 'Sqls' 'Py' -> 'PyPy' 'S' -> ''
Line by line
Lines 2-3
Strings shorter than 2 characters return an empty string, as the task asks.
Line 4
text[:2] is the first two characters and text[-2:] the last two.
Note
For “Py” the two slices overlap, so the result is “PyPy”.
Learn the concept
New to this topic? Read the lesson, then come back.