First and last 2 characters

EasyString Programs · 1 of 106

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.

Advertisement
Input
"Sqatools", "Py", "S"
Output
'Sqatools' -> 'Sqls'
'Py' -> 'PyPy'
'S' -> ''

Approach

  1. Check the length first; then join two slices.

Solution

Python
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”.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs