Start learning free

LESSON 395 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v3 — Delete Chars (-d) in Python

Practice

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

    Tr V3 in Python

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free