maciek2791 maciek2791 - 3 months ago 23
Python Question

Put variable inside string + hardcoded %d value

I'm trying to put into string variables and hardcoded '%d' value - which is not variable (unfornatelly python take it as intiger variable). Example:

Error="""awk -v col="%s" -F"," '{ if(NF != col) printf("Index: %d, NR, NF-1); }' "%s" > %s"""%(variable1,variable2,variable3)


Now I got an error:

TypeError: %d format: a number is required, not str.


So the main problem is "%d" value, I was trying with """%d""" , /%d/ but it does not work.

How to do that ?

J F J F
Answer

Try this:

Error="""awk -v col="%s" -F"," '{ if(NF != col) printf("Index: %%d, NR, NF-1); }' "%s" > %s"""%(variable1,variable2,variable3)

This uses %%, which resolves to %. Another solution:

Error="""awk -v col="{}" -F"," '{ if(NF != col) printf("Index: %d, NR, NF-1); }' "{}" > {}""".format(variable1,variable2,variable3)

This uses the new format strings.

Comments