0

(Please note python version is 2.7) Hi I have following DATBASE variable

_USER = 'sample'

DATABASES = {
    'stage': ('dbname=' + _USER + '-somedb host=' +_USER+ '-example.com'
           ' user=super password=pass'),
    'prod': ('dbname=' +_USER+ '-somedb host=' +_USER+ '-example.com'
           ' user=super password=pass'),
}

it translates to:

DATABASES = {
    'stage': ('dbname=sample-somedb host=sample-example.com'
           ' user=super password=pass'),
    'prod': ('dbname=sample-somedb host=sample-example.com'
           ' user=super password=pass'),
}

Is there a better way to replace _USER with sample? I tried using %s but that obviously doesn't work.

1 Answer 1

1

You could use str.format as follows:

_USER = 'sample'

DATABASES = {
    'stage': ('dbname={user}-somedb host={user}-example.com'.format(user=_USER) +
           ' user=super password=pass'),
    'prod': ('dbname={user}-somedb host={user}-example.com'.format(user=_USER) +
           ' user=super password=pass'),
}

Ref: https://docs.python.org/3/library/string.html#string-formatting

Note that we now need a + at the end of the row to concatenate strings.

Using str.format you can have different variables inside your string and also specify options.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.