A local configuration file contains a setting such as mode=fast.
What You Need to Understand
Use partition("=") to split a simple key-value line at its first equals sign, leaving additional equals signs in the value. Validate that the separator exists and that the key is not blank.
When to Use It
A local configuration file contains a setting such as mode=fast.
Step-by-Step Python Example
setting_line = "region=west=2"
name, separator, value = setting_line.partition("=")
if separator and name:
print(f"Setting {name} has value {value}")
else:
print("Invalid setting")
How the Example Works
The key is region; the value is west=2 because only the first separator is used.
Example Output
Setting region has value west=2
('theme', 'dark')
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
line = "theme=dark"
key, found, value = line.partition("=")
print((key, value) if found else None)
Important Behavior and Edge Cases
This example is not a complete INI parser: it does not handle comments, escapes or nested syntax. Use configparser for real INI files.
Try It Yourself
Handle lines that have no equals sign and lines whose key contains whitespace.
Common Beginner Mistakes
- This example is not a complete INI parser: it does not handle comments, escapes or nested syntax. Use
configparserfor real INI files. - Applying a string method before defining whether text is intended for display, comparison, parsing, or input validation.
Key Takeaways
- Use
partition("=")to split a simple key-value line at its first equals sign, leaving additional equals signs in the value. - The key is
region; the value iswest=2because only the first separator is used. - This example is not a complete INI parser: it does not handle comments, escapes or nested syntax.