Start learning free

LESSON 26 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in Python: Translating a Set with maketrans()

Practice Read the full explanation

Build a more powerful version of the Unix tr command. Given a list of lines and two equal-length strings set1 and set2, replace every character in each line that appears in set1 at index i with set2[i]. Characters not in set1 are unchanged. Return the lines joined by newline characters (\n).

Notes: set1 and set2 have the same length, contain only ASCII characters, and set1 has no repeated character. Characters are taken literally: there are no ranges like a-z. All replacements happen at once, so set1 = "ab", set2 = "ba" swaps the two letters. Lines may be empty.

Function signature:

def tr(self, lines: List[str], set1: str, set2: str) -> str:

Example:

Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC"

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Python has a built-in helper for exactly this. str.maketrans(set1, set2) builds a translation table mapping each char in set1 to the corresponding char in set2; line.translate(table) applies it.

The full solution:
class Solution:
    def tr(self, lines, set1, set2):
        table = str.maketrans(set1, set2)
        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 V2 in Python, explained

    Problem overview

    The second version of the tr tool translates a whole set of characters at once. The method tr receives a list of lines and two strings of equal length, set1 and set2. In every line, a character found at index i of set1 is replaced by set2[i]; other characters are unchanged. The lines are returned joined by "\n".

    For ["banana", "cherry"] with set1 = "abc" and set2 = "ABC", the result is "BAnAnA\nCherry". The characters are literal, with no ranges such as a-z, the sets have equal length, and set1 has no repeated character. Lines may be empty.

    One rule shapes the solution: all replacements happen at once. With set1 = "ab" and set2 = "ba", the two letters swap places.

    Approach: build a table once, translate each line with it

    The previous version used replace for one character. Chaining replace calls for each pair of the sets fails when replacements overlap: "banana".replace("a", "b").replace("b", "a") gives "aanana", because the second call also changes the bs the first call just made. A swap needs a different tool.

    Python's string method translate does the whole job in one pass over the line. It takes a translation table, and str.maketrans(set1, set2) builds that table by pairing the characters of the two strings by position. For "abc" and "ABC" the table is {97: 65, 98: 66, 99: 67}, a dictionary from character codes to character codes. Characters that are not in the table pass through unchanged. With the table maketrans("ab", "ba"), "banana".translate(table) gives "abnbnb": every letter is looked up independently, so nothing is translated twice.

    Step by step

    1. Build table = str.maketrans(set1, set2). The first character of set1 pairs with the first of set2, and so on. Build it once, before the loop.
    2. Create an empty list result.
    3. Write a for loop with line taking 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 tr(self, lines, set1, set2):
            table = str.maketrans(set1, set2)
            result = []
            for line in lines:
                result.append(line.translate(table))
            return "\n".join(result)
    

    Details to remember:

    • maketrans is called on the class, str.maketrans, and does not depend on any particular string.
    • The two strings must have the same length. Otherwise Python raises ValueError: the first two maketrans arguments must have equal length. The lesson guarantees equal lengths, so no check is needed.
    • Building the table once is cheaper than rebuilding it for each line, and keeps the loop body to one line.
    • As with every string method, translate returns a new string. The original line is unchanged.

    Complexity

    Building the table costs time proportional to the length of the sets. Translating a line costs one dictionary lookup per character, so the total time is linear in the number of characters in all lines, plus the size of the sets. The table and the output need extra space of the same order.

    Edge cases and common mistakes

    linesset1set2result
    ["banana", "cherry"]"abc""ABC""BAnAnA\nCherry"
    ["banana", "ab"]"ab""ba""abnbnb\nba"
    ["hello"]"""""hello"
    • The second row is the swap: every a becomes b and every b becomes a, in the same pass.
    • Chaining replace calls, one per pair, breaks the swap, as the "aanana" example above shows.
    • Case matters: with set1 = "abc", an uppercase "C" is not translated.
    • Empty lines translate to empty lines and still occupy their place in the output.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free