string manipulation
substring
programming
coding tutorial
text processing

How to get last 4 characters of a string?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Getting the last four characters of a string is a common utility for masking identifiers, formatting logs, and displaying compact labels. The happy path is short, but production code should define behavior for empty input, short strings, and Unicode-heavy text. A small helper function with tests is usually the safest approach.

Core Rule and Expected Behavior

Before writing code, define expected output:

  • If text length is at least four, return trailing four characters.
  • If text length is shorter, return whole text or a fallback, depending on product needs.
  • If input is null-like, return empty string or raise error consistently.

Explicit rules avoid subtle differences across services and user interfaces.

Python Implementation

Python slicing handles short strings gracefully.

python
1def last4(text: str) -> str:
2    return text[-4:]
3
4print(last4("ABCDEFG"))  # DEFG
5print(last4("AB"))       # AB
6print(last4(""))         # ""

For optional input values:

python
1from typing import Optional
2
3
4def safe_last4(text: Optional[str]) -> str:
5    if text is None:
6        return ""
7    return text[-4:]

This pattern is concise and predictable.

JavaScript Implementation

JavaScript uses slice with negative index.

javascript
1function last4(text) {
2  return String(text).slice(-4);
3}
4
5console.log(last4("ABCDEFG")); // DEFG
6console.log(last4("AB"));      // AB
7console.log(last4(""));        // ""

If null values should not be coerced, validate first instead of calling String.

javascript
1function strictLast4(text) {
2  if (text == null) return "";
3  return text.slice(-4);
4}

C Sharp Implementation

In modern C Sharp, range syntax is readable and safe with length checks.

csharp
1using System;
2
3static string Last4(string input)
4{
5    if (string.IsNullOrEmpty(input)) return string.Empty;
6    return input.Length <= 4 ? input : input[^4..];
7}
8
9Console.WriteLine(Last4("ABCDEFG"));
10Console.WriteLine(Last4("AB"));

For older language versions, use Substring after computing start index.

csharp
1static string Last4Legacy(string input)
2{
3    if (string.IsNullOrEmpty(input)) return string.Empty;
4    int start = Math.Max(0, input.Length - 4);
5    return input.Substring(start);
6}

Practical Masking Example

Trailing characters are often used for redacted display.

python
1def mask_account(account: str) -> str:
2    cleaned = ''.join(ch for ch in account if ch.isalnum())
3    if not cleaned:
4        return ""
5    return "****" + cleaned[-4:]
6
7print(mask_account("1234-5678-9012-3456"))

Important reminder: masking style may be regulated. Confirm security policy before exposing suffix values in logs or UI.

Unicode and User-Visible Characters

Some languages and emoji sequences use multiple code units per visual character. Basic slicing often works for identifier strings but can split visual glyphs in multilingual text.

If you need user-visible character accuracy, use grapheme-aware libraries rather than raw index slicing.

For example, in Python, package support for grapheme clusters can help when UI output must preserve composed symbols.

Testing Strategy

Add focused tests covering boundary cases.

python
1def test_last4():
2    assert last4("ABCDEFG") == "DEFG"
3    assert last4("AB") == "AB"
4    assert last4("") == ""

Also test representative Unicode and normalized text if your product handles international input.

Automated tests are the easiest way to keep helper behavior stable when code is reused in multiple modules.

Common Pitfalls

  • Assuming every string has at least four characters. Fix by defining short-input behavior explicitly.
  • Crashing on null input. Fix with guard clauses or typed non-null contracts.
  • Repeating suffix logic in many places. Fix by centralizing a shared helper.
  • Mixing normalized and formatted identifiers before slicing. Fix by cleaning input consistently first.
  • Ignoring Unicode grapheme behavior when displaying user-facing text. Fix with grapheme-aware processing when needed.

Summary

  • Last-four extraction is simple, but edge-case policy should be explicit.
  • Most languages provide safe slicing APIs for short strings.
  • Add null handling and input normalization for production reliability.
  • Centralize helper functions to avoid inconsistent behavior.
  • Test boundary and Unicode scenarios when output is user visible.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.