string manipulation
programming tutorial
substring removal
coding tips
text processing

Remove the last three characters from 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

Removing the last three characters from a string is simple in most languages, but the correct implementation still depends on edge cases such as short input, Unicode text, and whether failure should be silent or explicit. In Python, slicing is the usual answer, but it helps to be deliberate about the behavior you want.

The Basic Python Solution

In Python, the standard expression is text[:-3].

python
1def remove_last_three(text: str) -> str:
2    return text[:-3]
3
4print(remove_last_three("abcdef"))

This returns every character except the last three. It is concise, readable, and usually all you need.

Understand What Happens With Short Strings

Python slicing is forgiving. If the string has fewer than three characters, the result is an empty string rather than an exception.

python
print("hi"[:-3])
print(""[:-3])

That is often convenient, but it is not always the right business behavior. Sometimes a too-short string should be treated as invalid input.

Add a Strict Variant When Length Matters

If short strings should be rejected, validate first.

python
1def remove_last_three_strict(text: str) -> str:
2    if len(text) < 3:
3        raise ValueError("string must contain at least three characters")
4    return text[:-3]
5
6try:
7    print(remove_last_three_strict("go"))
8except ValueError as exc:
9    print("error:", exc)

The key is to choose deliberately between lenient and strict behavior rather than letting a default decide silently.

Generalize the Pattern

If this operation appears in several places, a reusable helper is clearer than repeating a magic number in many files.

python
1def trim_suffix_chars(text: str, count: int, *, strict: bool = False) -> str:
2    if strict and len(text) < count:
3        raise ValueError("input shorter than requested trim count")
4    return text[:-count] if count > 0 else text
5
6print(trim_suffix_chars("report.csv", 4))
7print(trim_suffix_chars("abc", 3))

This keeps the logic explicit and makes later changes easier.

Fixed Character Removal vs Real Suffix Removal

Dropping the last three characters is not always the same as removing a known suffix. If the intent is "remove .csv when present," checking the actual suffix is safer than blindly trimming by length.

python
1def remove_suffix(text: str, suffix: str) -> str:
2    if text.endswith(suffix):
3        return text[:-len(suffix)]
4    return text
5
6print(remove_suffix("report.csv", ".csv"))
7print(remove_suffix("report.txt", ".csv"))

This avoids accidental truncation when the input does not match the expected ending.

Think About Unicode and Display Semantics

Python string slicing works on Unicode code points, which is usually what you want. But user-facing text can contain combined emoji or grapheme clusters that do not align perfectly with visual characters.

python
s = "helloπŸ™‚πŸ™‚πŸ™‚"
print(s[:-3])

For most plain text and identifiers, ordinary slicing is fine. For advanced user-facing text editing, especially around emoji or composed characters, you may need a grapheme-aware library instead of raw slicing.

Batch Processing Example

If you need to trim many strings, use a clear list comprehension or map-like transformation rather than scattering slicing inline throughout the pipeline.

python
rows = ["abcXYZ", "helloXYZ", "short"]
trimmed = [value[:-3] if len(value) >= 3 else value for value in rows]
print(trimmed)

This is small, but it still benefits from having a documented rule for short strings.

Common Pitfalls

The most common mistake is forgetting that slicing short strings does not raise an error. If too-short input is invalid, add validation.

Another issue is using a fixed-length trim when the real intent is suffix removal. In that case, check the suffix instead of blindly cutting characters.

Developers also sometimes repeat magic numbers in many places instead of creating one clear helper function.

Finally, for user-facing text with complex Unicode composition, raw slicing may not match perceived character boundaries even though the code is technically correct.

Summary

  • In Python, text[:-3] is the standard way to remove the last three characters.
  • Short strings return an empty string unless you add explicit validation.
  • Use a helper when the same trimming rule appears in multiple places.
  • Prefer actual suffix checks when the goal is to remove a known ending rather than a fixed count.
  • Be cautious with complex Unicode text if visual character boundaries matter.

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.