Start learning free

LESSON 627 OF 673 · PROJECTS: COMMAND-LINE TOOLS

Tr V3 in Python: Deleting Characters with maketrans()

Practice Read the full explanation

Build a version of the Unix tr -d command. Given a list of lines and a string chars, remove every character that appears in chars from each line, then return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Upper and lower case are different characters. A line can become empty after deleting, and then it stays as an empty line in the output.

Function signature:

def trDelete(self, lines: List[str], chars: str) -> str:

Example:

Input: lines = ["banana", "apple"], chars = "aeiou"

Output: "bnn\nppl"

When printed:
bnn
ppl

Python's str.maketrans takes a third argument: a string of characters to delete. Pair it with line.translate(table) to get a delete-only translation.

The full solution:
class Solution:
    def trDelete(self, lines, chars):
        table = str.maketrans('', '', chars)
        result = []
        for line in lines:
            result.append(line.translate(table))
        return "\n".join(result)

STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in Python, explained

    Problem overview

    The third version of the tr tool mimics tr -d. The method trDelete receives a list of lines and a string chars. It removes from every line each character that appears in chars, then returns the lines joined by "\n".

    For ["banana", "apple"] and chars = "aeiou", the result is "bnn\nppl". The string chars is non-empty, its characters are taken literally with no ranges, and case matters. A line can become empty after the deletion, and it then stays in the output as an empty line.

    Approach: the third argument of maketrans

    The previous version translated characters with a table made by str.maketrans(set1, set2) and applied it with translate. The same machinery can delete. str.maketrans accepts a third argument, a string of characters to delete. When the first two strings are empty, nothing is swapped, and every character of the third string is mapped to None, which translate reads as "drop this character".

    For example, str.maketrans('', '', "ab") gives {97: None, 98: None}. Characters that the table doesn't mention are kept as they are, so one translate call per line is all that is needed.

    The deletion applies to every line independently. With chars = "an", the line "banana" becomes "b", and "hello" with chars = "l" becomes "heo", while the original "hello" is unchanged. Strings are immutable, so translate builds a new string each time.

    The three arguments can also be combined: str.maketrans('a', 'A', 'n') gives {97: 65, 110: None}, which swaps a for A and deletes n. This lesson needs only the deleting part.

    Step by step

    1. Build table = str.maketrans('', '', chars). The two empty strings mean there are no swaps; only the third argument matters.
    2. Create an empty list result.
    3. Write a for loop where line takes each whole line of lines.
    4. Inside the loop, append line.translate(table) to result.
    5. After the loop, return "\n".join(result).

    The solution in Python

    class Solution:
        def trDelete(self, lines, chars):
            table = str.maketrans('', '', chars)
            result = []
            for line in lines:
                result.append(line.translate(table))
            return "\n".join(result)
    

    A few remarks:

    • The table is built once, outside the loop, and reused for every line.
    • The quotes in '' are two single quotes: an empty string. Writing "" is equivalent.
    • A repeated character in chars is harmless: the table simply maps it to None twice.
    • translate returns a new string, so each original line is untouched.

    Complexity

    Building the table is proportional to the length of chars. Each line is processed with one dictionary lookup per character, so the total time is linear in the number of characters in all lines. The result needs extra space of the same order.

    Edge cases and common mistakes

    linescharsresult
    ["banana", "apple"]"aeiou""bnn\nppl"
    ["aaa", "bob"]"ab""\no"
    ["banana"]"A""banana"
    • In the second row, "aaa" loses all its characters and becomes an empty line, which still takes its place in the output: the result starts with a newline, then "o". Skipping empty lines would be a mistake.
    • In the third row, case matters: an uppercase "A" does not delete lowercase "a".
    • Putting the characters in the first or second argument of maketrans instead of the third gives a table that swaps characters, or raises an error for unequal lengths, rather than deleting.
    • Calling replace once per character of chars also works, but a loop inside a loop is more code than a single table.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free