Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ValueError: expected ':' after format specifier

Tags:

python

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.

like image 872
rreichel Avatar asked Mar 04 '26 17:03

rreichel


2 Answers

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.

like image 78
gtlambert Avatar answered Mar 06 '26 05:03

gtlambert


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.

like image 37
python Avatar answered Mar 06 '26 07:03

python