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.
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.
For optional input values:
This pattern is concise and predictable.
JavaScript Implementation
JavaScript uses slice with negative index.
If null values should not be coerced, validate first instead of calling String.
C Sharp Implementation
In modern C Sharp, range syntax is readable and safe with length checks.
For older language versions, use Substring after computing start index.
Practical Masking Example
Trailing characters are often used for redacted display.
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.
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
- How to grep a yaml value
- How to increase weight of a word for CountVectorizer
- How to initialize word-embeddings for Out of Vocabulary Word?
- How to load the saved tokenizer from pretrained model
- How to make the tensorflow hub embeddings servable using tensorflow serving?
- How to make use of pre-trained word embeddings when training a model in sklearn?
- How to Merge Numerical and Embedding Sequential Models to treat categories in \`RNN\`
- How to Merge Numerical and Embedding Sequential Models to treat categories in `RNN`
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.