2

I'm trying to have a script to generate some makefiles for me. I want to format this multiline string, but I'm getting a strange error.

Code:

make_content = """ PCC = pgcc 
%(bench)_serial: src/main.c src/%(bench)_serial.c ../common/util.c
\t$(PCC) $(ACCFLAGS) -o bin/%(bench)_serial src/main.c src/%(bench)_serial.c

clean:
\trm -rf *.o *.oo bin/*""" % {'bench':'umpalumpa'}

Error:

Traceback (most recent call last):
  File "./new_bench.py", line 27, in <module>
    \trm -rf *.o *.oo bin/*""" % {'bench':'umpalumpa'}
ValueError: unsupported format character '_' (0x5f) at index 21

Any ideas?

Notes: this is a truncated version of the makefile, no comments on that. Notes[2]: 'umpalumpa' is a placeholder to make sure it's a string. It'll be something real one day.

Edit: I'm using python 2.7

2 Answers 2

6

As you have already got the answer as to why that didn't work, a better way and also recommended to use if format function (If you are using `Python 2.6+): -

"src/{bench}_serial.c".format(bench='umpalumpa')

So, for your string, it becomes: -

ake_content = """ PCC = pgcc 
{bench}_serial: src/main.c src/{bench}_serial.c ../common/util.c
\t$(PCC) $(ACCFLAGS) -o bin/{bench}_serial src/main.c src/{bench}_serial.c

clean:
\trm -rf *.o *.oo bin/*""".format(bench='umpalumpa')
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't really answer his question of why he's getting that error. It also only works in Python 2.6+, so while usually fine, it can cause compatibility problems if older versions of Python need to be supported.
@agf. I just posted it, because his problem was already solved by prevoius answer. and there is no point in duplicating the answer. right?
@agf. I think this answer is far eligible to stand as answer, rather than a comment.
5

You need to specify a conversion type after the mapping key:

"%(bench)s_serial" % {'bench':'umpalumpa'}

Note the s before the underscore. The output here would still be "umpalumpa_serial".

The conversion type is always required and always last, after the % and any optional components.

There is no difference between formatting a triple-quoted string literal and a single quoted string literal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.