Reputation: 661
(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.
Upvotes: 0
Views: 61
Reputation: 53
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.
Upvotes: 1