Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Mask all but the last four characters

Replace all characters in a string with a mask character except for the final four characters.

Python practice15 minString PatternsIntermediateLast updated March 18, 2026

Problem statement

Many systems display only the last few characters of sensitive identifiers (e.g., credit cards, account numbers) and mask the rest. Implement a function mask_all_but_last4(s, mask_char='*') that converts the input to a string and replaces every character except the final four with mask_char. If the string has length 4 or less, return it unchanged. The mask_char must be a single-character string.

Task

Write a function that masks all characters of an input (converted to string) except the last four, using a single-character mask.

Examples

Basic masking

Input

mask_all_but_last4('1234567890')

Output

'******7890'

Input length 10 -> first 6 characters masked, final 4 kept.

Input format

A value s (any type) and optionally a single-character mask_char.

Output format

A string with all but the last four characters replaced by mask_char.

Constraints

Do not use external libraries. Convert non-string inputs to string. mask_char must be a single-character string.

Samples

Sample 1

Input

mask_all_but_last4('abcd')

Output

'abcd'

Strings of length 4 are returned unchanged.