'Python string manipulation multiple occurances with same variable

(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.



Solution 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sylven