I'm using a dict in python in an attempt to replace words in a string with whatever is in the dict. When I try to run my code, however, it prints out the error "ValueError: expected ':' after format specifier." I have no idea where this error might be coming from. Does anyone with more pythonic wisdom have any suggestions for me? Thanks!
Here's an example of my code:
str = """{fruit}"""
dict = {"fruit":"pears"}
str.replace(**dict)
This should make str contain "pears".
UPDATE
I'm purposefully using the triple quoted strings - in my code I'm trying to do a replace with a multiline string, Also, my code is already using the .format method. I just decided to mix the words when translating it between my code to here. This is an updated version of my example code that isn't working.
my_dict = """{fruit}"""
dict = {"fruit":"pears"}
string.format(**my_dict)
FINAL UPDATE
Thanks for all of the answers I received below. I didn't do a good job of explaining my problem and decided to simplify it which simplified away my problem. I'm doing some meta programming so I was trying to replace within a C function definition and python was trying to use the "{" as a format identifier. I needed to use "{{" to get python to recognize the bracket as a char and not as some beginning to a format identifier.
You want to use the format() function instead of replace():
string = "{fruit}"
my_dict = {"fruit": "pears"}
print(string.format(**my_dict))
Output
pears
A couple of other things: you shouldn't use the Python keywords str and dict as variable names. I have changed your variable names for clarity.
Also, you were using a multi-line string with triple quotes for no particular reason, so I changed that too.
Another simple method to replace sentence with a dictionary. I hope you like the simplicity. Also look into this Single Pass Multiple Replace
import re
s = "node.js ruby python python3 python3.6"
d = {'python': 'python2.7', 'python3': 'python3.5', 'python3.6': 'python3.7'}
pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b')
result = pattern.sub(lambda x: d[x.group()], s)
print result
This will match whole words only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With