3

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.

2
  • 1
    Can you elaborate? This raises TypeError: replace() takes no keyword arguments here, as it should. Commented Jan 29, 2016 at 15:41
  • 1
    Shoot I am using the format function already. For some reason I decided to call it replace >.< Commented Jan 29, 2016 at 15:45

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hey! Thanks for answering - I just realized that I meant to say format instead of replace. I'm using the format function already. Also I was using the triple quotes because in my larger application it is a multi-line string. This is all information I should have provided to begin with. I'll go update my question to reflect this clarification. And thanks for the correction on variable names!
If you are using format already then your code should work fine!
Hm, I'm still getting the ValueError: expected ':' after format specifier error. Could it be that some piece of code isn't correctly adding to the dictionary?
There must be something else incorrect in your code. My example works
2

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.

2 Comments

That's a very fragile way to do it. There is no delimiter, so 'pythonic' will become 'python3.3ic', and if any of the words in word_mapping is a prefix of another then either could be used for the replacement: word_mapping = {'python': 'python2.7', 'python3': 'python3.5'} could turn python3 into either python2.73 or python3.5 and you won't know which.
Yes, you're right! I have edited my answer, now it will match whole words only!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.