Skip to content

Instantly share code, notes, and snippets.

@ssirois
Created May 18, 2018 16:43
Show Gist options
  • Save ssirois/7f1b09b2987397fe2635235346771a33 to your computer and use it in GitHub Desktop.
Save ssirois/7f1b09b2987397fe2635235346771a33 to your computer and use it in GitHub Desktop.
Python string builder ?
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()
@ssirois
Copy link
Author

ssirois commented May 18, 2018

What's a better python way to clean lines 8-11?

@erozqba
Copy link

erozqba commented May 18, 2018

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) +
            "}"
        )

@ventilooo
Copy link

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.

@ssirois
Copy link
Author

ssirois commented May 18, 2018

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