Normalize a config value
Problem statement
Values copied from config files often have stray spaces, a trailing newline, or mixed case. Given raw = " Production \n", clean it so it has no surrounding whitespace and is all lowercase, then print it between square brackets:
[production]
The brackets make it easy to see that no spaces are left.
Examples
Example 1
Input: raw = " Production \n"
Output: [production]
Hints
Approach
Optimal
Strings come with built-in methods, called with a dot after the value. .strip() returns a new string with whitespace (spaces, tabs, newlines) removed from the start and end, but not from the middle. .lower() returns a lowercase copy. Because each method returns a new string, you can chain them in one expression. Strings in Python never change in place, so you must store the result in a variable (here env). Printing it inside brackets confirms there are no hidden spaces.
raw = " Production \n" env = raw.strip().lower()print(f"[{env}]")Follow-up questions
- Print
Deploying to productiononly if the cleaned value equalsproduction. - Use
.replace("-", "_")to turnmy-app-prodintomy_app_prod.
Frequently asked questions
String methods return a new string instead of changing the original. Write raw = raw.strip() or save the result in a new variable.
A comparison like env == "production" silently fails if the value is "Production \n". Normalizing input first avoids a whole class of confusing bugs.