Issue
I want to write two strings into a file with variable white-spaces between. Here's the code I wrote:
width = 6
with open(out_file, 'a') as file:
file.write("{:width}{:width}\n".format('a', 'b'))
But I get ValueError: Invalid conversion specification
from it. I expected it to write characters a and b with 6 spaces between in one line into the file.
I am using python 2.
Solution
You need to change the format string a little and pass width
as a keyword argument to the format()
method:
width = 6
with open(out_file, 'a') as file:
file.write("{:{width}}{:{width}}\n".format('a', 'b', width=width))
Contents of file afterwards:
a b
Answered By - martineau
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.