Programming
String Manipulation
Coding Tips
Computer Science
Software Development

Delete first character of string if it is 0

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

A common cleanup step is to remove a leading zero from a string, but only when that zero is the first character. This shows up in imported identifiers, phone fragments, fixed-width data, and user input that was padded for display rather than meaning.

The key detail is that you usually want to remove one character conditionally, not “strip all zeros” and not convert the value to a number unless the data is truly numeric.

Check the First Character Explicitly

If the rule is “drop the first character only when it is 0,” the simplest solution is to test the prefix and slice the remainder.

python
1def drop_one_leading_zero(value: str) -> str:
2    if value.startswith("0"):
3        return value[1:]
4    return value
5
6
7samples = ["01234", "1234", "0", "", "00123"]
8for sample in samples:
9    print(f"{sample!r} -> {drop_one_leading_zero(sample)!r}")

Output:

text
1'01234' -> '1234'
2'1234' -> '1234'
3'0' -> ''
4'' -> ''
5'00123' -> '0123'

This implementation is precise. It removes at most one character and leaves the rest of the string untouched.

Why Numeric Conversion Is Often the Wrong Tool

A tempting shortcut is to parse the string as an integer and then convert it back. That changes more than the first character:

  • it removes all leading zeros
  • it fails on non-numeric strings like "01A7"
  • it may lose formatting that matters to downstream code

For example, an order code like "00123A" is not a number even though it begins with digits. In that case, string slicing is the correct operation because you are transforming text, not doing arithmetic.

Equivalent Solutions in Other Languages

The same idea translates directly to most languages.

javascript
1function dropOneLeadingZero(value) {
2  return value.startsWith("0") ? value.slice(1) : value;
3}
4
5console.log(dropOneLeadingZero("01234"));
6console.log(dropOneLeadingZero("1234"));
7console.log(dropOneLeadingZero("00123"));
java
1public class Main {
2    static String dropOneLeadingZero(String value) {
3        if (value != null && value.startsWith("0")) {
4            return value.substring(1);
5        }
6        return value;
7    }
8
9    public static void main(String[] args) {
10        System.out.println(dropOneLeadingZero("01234"));
11        System.out.println(dropOneLeadingZero("1234"));
12        System.out.println(dropOneLeadingZero("00123"));
13    }
14}

These examples all encode the same rule: inspect the first character, then slice once.

Decide Whether Empty String Is Acceptable

When the input is exactly "0", removing the first character produces an empty string. That is correct for some applications and wrong for others.

If you need to keep at least one digit, add a small guard:

python
1def normalize_account_fragment(value: str) -> str:
2    if value == "0":
3        return "0"
4    if value.startswith("0"):
5        return value[1:]
6    return value

That distinction should be a business rule, not an accident. The string operation itself is simple, but the expected output may vary by domain.

One Leading Zero Versus All Leading Zeros

Be explicit about what the requirement means. These are different operations:

  • remove the first character if it is 0
  • remove exactly one leading zero
  • remove all leading zeros

If the actual requirement is to remove every leading zero, use a loop or a regular expression instead.

python
1def strip_all_leading_zeros(value: str) -> str:
2    index = 0
3    while index < len(value) and value[index] == "0":
4        index += 1
5    return value[index:]

That function is useful, but it solves a different problem from the title of this article.

Common Pitfalls

  • Converting the string to an integer and back. That changes formatting and removes more than one leading zero.
  • Forgetting the empty-string case. Accessing value[0] directly can raise an error when the input is "".
  • Removing all leading zeros when the rule only allows removing one.
  • Returning an empty string for "0" without checking whether the application expects a placeholder digit.
  • Applying the cleanup to identifiers, postal codes, or product codes that treat leading zeros as meaningful data.

Summary

  • The safest implementation checks the first character and slices once.
  • String slicing is better than numeric conversion when the value is textual data.
  • Decide early whether "0" should become "" or remain "0".
  • “Remove one leading zero” and “strip all leading zeros” are different requirements.
  • Simple prefix logic is readable, fast, and portable across languages.

Course illustration
Course illustration

All Rights Reserved.