Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String substitution using dictionary

I am learning python and working on strings to find a better way for string substitution using dictionary

I have a string which contains my custom placeholders as below:

placeholder_prefix = '$['
placeholder_suffix = ']'

dict={'key1':'string','key2':placeholders}
msg='This $[key1] contains custom $[key2]'

I want the placeholders('prefix-suffix' and 'keys') should be replaced by 'value' from the dictionary as below:

'This string contains custom placeholders'

I am able to get message as: 'This [string] contains custom [placeholders]' by writing function:

def replace_all(text):
    for key, value in brand_dictionary.iteritems():
        text = text.replace(key, value).replace('$[', '[')        
    return text

I can try different replace to remove '$[' and ']' but that could replace any character (like '$','[', ']') contained as a part of message itself(not as part of placeholder). So i want to avoid this and replace only for custom placeholders.

I can think of regular expression(for placeholders) but since my message contains multiple keys so seems it may not be useful?

Is there a better way to do it in python?

like image 907
akhi Avatar asked Jul 01 '15 12:07

akhi


People also ask

Can dictionary values be a string?

Dictionary values can be just about anything (int, lists, functions, strings, etc).

How do you turn a string of a dictionary into a dictionary?

To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function. Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.

Can a dictionary key Be a string?

The keys of a dictionary can be any kind of immutable type, which includes: strings, numbers, and tuples: mydict = {"hello": "world", 0: "a", 1: "b", "2": "not a number" (1, 2, 3): "a tuple!"}


4 Answers

Try this:

dict={key1:'string',key2:placeholders}

msg='This {key1} contains custom {key2}'.format(**dict)

Example I ran:

>>> msg="hello {a} {b}"
>>> t={"a":"aa","b":"bb"}
>>> msg="hello {a} {b}".format(**t)
>>> msg
'hello aa bb'
like image 167
Avinash Garg Avatar answered Oct 19 '22 03:10

Avinash Garg


As a more general way you can use re.sub with a proper replace function :

>>> d={'key1':'string','key2':'placeholders'}
>>> re.sub(r'\$\[([^\]]*)\]',lambda x:d.get(x.group(1)),msg)
'This string contains custom placeholders'

The advantage of using regex is that it refuses to match the placeholder characters within string that doesn't have the expected format!

Or as a simpler way you could use string formatting as following:

In [123]: d={'key1':'string','key2':'placeholders'}
     ...: msg='This {key1} contains custom {key2}'
     ...: 
     ...: 

In [124]: msg.format(**d)
Out[124]: 'This string contains custom placeholders'

Or instead of using a dictionary if number of your variables is not that big you can have your keys as variables that are accessible in current namespace and then use f-strings which is feature introduced since Python-3.6:

In [125]: key1='string'
     ...: key2= 'placeholders'
     ...: msg=f'This {key1} contains custom {key2}'
     ...: 

In [126]: msg
Out[126]: 'This string contains custom placeholders'
like image 26
Mazdak Avatar answered Oct 19 '22 03:10

Mazdak


If you are okay with changing the placeholders, you can use - %(key)s - and the % operator to automatically apply the dict at those places.

Exmaple -

>>> dict={'key1':'string','key2':'placeholders'}
>>> msg='This %(key1)s contains custom %(key2)s'
>>> print(msg%dict)
This string contains custom placeholders
like image 1
Anand S Kumar Avatar answered Oct 19 '22 03:10

Anand S Kumar


Another option includes formatting with string substitution:

msg='This %(key1)s contains custom %(key2)s'
dict={'key1':'string','key2':'placeholders'}
print(msg%dict)

>> This string contains custom placeholders
like image 1
cacti5 Avatar answered Oct 19 '22 04:10

cacti5