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.
"Sqatools", "Py", "S"
'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)))'Sqatools' -> 'Sqls' 'Py' -> 'PyPy' 'S' -> ''
Line by line
Strings shorter than 2 characters return an empty string, as the task asks.
text[:2] is the first two characters and text[-2:] the last two.
For “Py” the two slices overlap, so the result is “PyPy”.
Learn the concept
New to this topic? Read the lesson, then come back.