Start learning free

LESSON 625 OF 673 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in Python: Swap One Character with replace()

Practice Read the full explanation

Build a tiny version of the Unix tr command. Given a list of lines and two single characters fromChar and toChar, replace every occurrence of fromChar with toChar in each line, then return the lines joined by newline characters (\n).

Notes: fromChar and toChar are single ASCII characters, taken literally (no escapes like \, no ranges). Upper and lower case are different characters. A line may be empty, and may not contain fromChar at all.

Function signature:

def tr(self, lines: List[str], fromChar: str, toChar: str) -> str:

Example:

Input: lines = ["banana", "apple"], fromChar = "a", toChar = "X"

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

Use Python's built-in string method replace(old, new) on each line, then join with "\n".

The full solution:
class Solution:
    def tr(self, lines, fromChar, toChar):
        result = []
        for line in lines:
            result.append(line.replace(fromChar, toChar))
        return "\n".join(result)

STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in Python, explained

    Problem overview

    This project builds a tiny version of the Unix tr command over several versions. In the first one, the method tr receives a list of lines and two single characters, fromChar and toChar. It replaces every fromChar with toChar in each line and returns the lines joined by "\n".

    For ["banana", "apple"] with fromChar = "a" and toChar = "X", the result is "bXnXnX\nXpple". Both characters are taken literally, with no escapes and no ranges, and upper and lower case are different characters. A line may be empty or may not contain fromChar at all.

    Approach

    The work splits in two. First translate each line on its own, then glue the translated lines into one string. Strings have a method that does the first part: line.replace(old, new) returns a new string in which every occurrence of old is replaced by new. Strings in Python are immutable, so replace never changes line itself; it hands back a fresh string, and you have to keep that result.

    The loop collects translated lines in a list and the last step joins them. Unlike a print statement per line, a single returned string has no newline at the end: "\n".join(result) puts the separator only between two lines.

    Step by step

    1. Create an empty list result for the translated lines.
    2. Write a for loop where line takes each whole line of lines. line is a string such as "banana", not one character.
    3. Inside the loop, append line.replace(fromChar, toChar) to result. This changes every occurrence, not only the first.
    4. After the loop, with no indent, return "\n".join(result). It runs once, when every line is translated.

    The solution in Python

    class Solution:
        def tr(self, lines, fromChar, toChar):
            result = []
            for line in lines:
                result.append(line.replace(fromChar, toChar))
            return "\n".join(result)
    

    Points worth knowing about replace:

    • It matches the text exactly, including case, so "A" does not match "a". With fromChar = "A", the input ["banana", "apple"] comes back unchanged as "banana\napple".
    • An empty line stays empty, and a line without fromChar comes back equal to itself. With ["", "cherry"], "a" and "X", the result is "\ncherry".
    • replace works on substrings, not on sets of characters. With fromChar = "an" and toChar = "X", the line "banana" becomes "bXXa": the whole text "an" is replaced as one unit. That cannot happen in this lesson, because both arguments are single characters.
    • The loop could be written as a list comprehension, but the step-by-step loop keeps each action visible.

    Complexity

    Each line is scanned once by replace and the join copies the text once more, so the time is linear in the total number of characters. The result list and the output string need space of the same order.

    Edge cases and common mistakes

    • Forgetting to keep the result. Calling line.replace(fromChar, toChar) on its own line and appending line returns the unchanged text, because strings are immutable.
    • Putting the return inside the loop, which returns after the first line.
    • Adding a newline after the last line. The join does not, and the lesson's output has none.
    • Expecting only the first occurrence to change. replace changes all of them; in "banana" all three "a"s become "X".

    The next version of the tool translates a whole set of characters at once.

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