An imported product code contains hyphens and spaces that must be normalized.
What You Need to Understand
The str.translate() method maps or removes Unicode characters according to a translation table. str.maketrans() is a convenient way to create that table. This works well for a fixed set of character substitutions.
When to Use It
An imported product code contains hyphens and spaces that must be normalized.
Step-by-Step Python Example
translation_table = str.maketrans({"-": "_", " ": None})
product_code = "AB-22 C"
print(product_code.translate(translation_table))
How the Example Works
The hyphen becomes an underscore; spaces are deleted because they map to None. The resulting string is AB_22C.
Example Output
AB_22C
grun
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
accent_map = str.maketrans("äöü", "aou")
print("grün".translate(accent_map))
Important Behavior and Edge Cases
This is character mapping, not a full validation system. Unknown characters remain unchanged, and substitutions can expand text if a table maps an ordinal to a longer string.
Try It Yourself
Add a rule that changes slashes to underscores, then test two product codes.
Common Beginner Mistakes
- This is character mapping, not a full validation system. Unknown characters remain unchanged, and substitutions can expand text if a table maps an ordinal to a longer string.
- Applying a string method before defining whether text is intended for display, comparison, parsing, or input validation.
Key Takeaways
- The
str.translate()method maps or removes Unicode characters according to a translation table. - The hyphen becomes an underscore; spaces are deleted because they map to
None. - This is character mapping, not a full validation system.