Home > Enterprise >  Python string manipulation multiple occurances with same variable
Python string manipulation multiple occurances with same variable

Time:05-11

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

CodePudding user response:

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.

  • Related