Back to Freecodecamp

Step 3

curriculum/challenges/english/blocks/learn-how-to-work-with-numbers-and-strings-by-implementing-the-luhn-algorithm/656877f71bba2b97acedf9af.md

latest1.7 KB
Original Source

--description--

Python comes with built-in classes that can help us with string manipulation. One of them is the str class. It has a method called maketrans that can help us create a translation table. This table can be used to replace characters in a string:

python
str.maketrans({'t': 'c', 'l': 'b'})

The above, when called on a string, will replace all t characters with c and all l characters with b.

Create a variable called card_translation and assign it a translation table to replace all - and characters with an empty string.

--hints--

You should create a card_translation variable within main.

js
({
    test: () => {
        const transformedCode = code.replace(/\r/g, "");
        const main = __helpers.python.getDef("\n" + transformedCode, "main");
        const { function_body } = main;

        assert.match(function_body, / +card_translation\s*=/);
    }
})

You should assign card_translation a value of str.maketrans({'-': '', ' ': ''}).

js
({
    test: () => {
        const transformedCode = code.replace(/\r/g, "");
        const main = __helpers.python.getDef("\n" + transformedCode, "main");
        const { function_body } = main;

        const allowedMatches = [
            / +card_translation\s*=\s*str\.maketrans\(\s*\{\s*('|")-\1\s*:\s*('|")\2\s*,\s*('|") \3\s*:\s*('|")\4\s*\}\s*\)/,
            / +card_translation\s*=\s*str\.maketrans\(\s*\{\s*('|") \1\s*:\s*('|")\2\s*,\s*('|")-\3\s*:\s*('|")\4\s*\}\s*\)/,
        ];
        const anyMatch = allowedMatches.some((match) => match.test(function_body));
        assert.isTrue(anyMatch);
    }
})

--seed--

--seed-contents--

py
--fcc-editable-region--
def main():
    card_number = '4111-1111-4555-1142'
    
--fcc-editable-region--