PracticeStrings

Clean a Product Label

EasyStringstraversalaccumulationstate tracking Time not estimated Not started

Context

An ecommerce catalog stores product labels that may contain characters needing masking before display. Given a label, a set of characters to mask, and one substitute character, create the display-safe label while preserving all other text exactly, including spaces and repeated characters.

Problem

Write a function that transforms a product label one character at a time. If the current character appears in the supplied list of characters to mask, append the substitute character to the result. Otherwise, append the original character. Preserve the original order, keep the result the same length as the label, and process every occurrence of every target character. Spaces and characters not listed for masking must remain unchanged.

Examples

Example 1
Input: label = "Apple Juice"mask_chars = ["p", "e"]substitute = "*"
Output: "A**l* Juic*"
Explanation: Example 1 executes to "A**l* Juic*".
Example 2
Input: label = "A1B-200"mask_chars = ["1", "2", "0"]substitute = "#"
Output: "A#B-###"
Explanation: Example 2 executes to "A#B-###".
Example 3
Input: label = "Fresh mint"mask_chars = ["m", "t"]substitute = "_"
Output: "Fresh _in_"
Explanation: Example 3 executes to "Fresh _in_".

Constraints

  • 0 <= len(label) <= 1000
  • 1 <= len(mask_chars) <= 26
  • 1 <= len(mask_chars[i]) <= 1 for every i
  • mask_chars: distinct elements
  • 1 <= len(substitute) <= 1
  • Types: label is str, mask_chars is str[], substitute is str; result is str

Function signature

def sanitize_product_label(label: str, mask_chars: list[str], substitute: str) -> str
label str
The product label to transform; it may be empty and may contain spaces.
mask_chars list[str]
Distinct one-character strings that must be replaced.
substitute str
The single character used for every replacement.
returns str
The transformed product label, with each listed character replaced by the substitute while all other characters retain their order and value.

Adapted from MBPP problem task_732 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Notes

  • The target collection is represented as a list so its members are distinct and each member is exactly one character.
Approved · t3-abs_132_v314 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1