Created
May 18, 2018 16:43
-
-
Save ssirois/7f1b09b2987397fe2635235346771a33 to your computer and use it in GitHub Desktop.
Python string builder ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ConfigurationFile(): | |
def __init__(self, config1, config2): | |
self._config1 = config1 | |
self._config2 = config2 | |
def output_file(self): | |
print( | |
"configuration-group={\n" | |
" config1=\"" + self._config1 + "\"\n" | |
" config2=\"" + self._config2 + "\"\n" | |
"}" | |
) | |
myConfigFile = ConfigurationFile('value of config 1', 'value of config 2') | |
myConfigFile.output_file() |
If you have a long config file, you could use Template:
from string import Template
class ConfigurationFile():
def __init__(self, config1, config2):
self._config1 = config1
self._config2 = config2
def output_file(self):
config = Template(
"""
configuration-group={
config1=$config1
config2=$config2
}
"""
)
print(config.substitute({'config1':self._config1, 'config2': self._config2}))
myConfigFile = ConfigurationFile('value of config 1', 'value of config 2')
myConfigFile.output_file()
if not, just use .format() :
print(
"configuration-group={\n" +
" config1={}\n".format(self._config1) +
" config2={}\n".format(self._config2) +
"}"
)
If you're using python 3.6 ; You could use f-strings
>>> name = 'Fred'
>>> age = 42
>>> f'He said his name is {name} and he is {age} years old.'
He said his name is Fred and he is 42 years old.
Thanks @erozqba and @ventilooo for the hints!
I'll check that out! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's a better python way to clean lines 8-11?