Reputation: 3218
In my piece of code, I have,
out.write(datGroup)
out.write(' '*20+": Space Group\n")
out.write(datLatx +" ")
out.write(datLaty +" ")
out.write(datLatz +" ")
out.write('/'),
out.write(' '*20+": a,b,c,alpha,beta,gamma\n")
which gives the output as:
189 : Space Group
10 11 12 / : a,b,c,alpha,beta,gamma
which is correct for what I have done, but not what I have want.
I want the ": Spacegroup" and ": a,b,c.." to start from the same column, irresepective of where the data of its row ended, like:
189 : Space Group
10 11 12 / : a,b,c,alpha,beta,gamma
Can I do that in python3?
EDIT after jonrsharpe's example So I have tried:
def write_row(out, data, header, col=20):
out.write("{0}: {1}".format(" ".join(map(str, data)).ljust(col), header))
def print_data(self, BSub):
.....
with open("Init", mode='w') as out:
write_row(out, (datGroup,), "Space Group")
which is giving error:
$ python3 geninit.py
Traceback (most recent call last):
File "geninit.py", line 109, in print_data
write_row(out, (datGroup,), "Space Group")
NameError: global name 'write_row' is not defined
Upvotes: 0
Views: 111
Reputation: 122061
I would create a function to do this, for example:
def print_row(data, header, col=20):
print("{0}: {1}".format(" ".join(map(str, data)).ljust(col), header))
Then call it for each case:
print_row((datGroup,), "Space Group")
print_row((datLatx, datLaty, datLatz), "a,b,c,alpha,beta,gamma")
This gives, for example
>>> datGroup = 189
>>> datLatx, datLaty, datLatz = 11, 12, 13
>>> print_row((datGroup,), "Space Group")
189 : Space Group
>>> print_row((datLatx, datLaty, datLatz, "/"), "a,b,c,alpha,beta,gamma")
11 12 13 / : a,b,c,alpha,beta,gamma
This uses:
map(str, ...)
to convert all of the data
into strings;" ".join(...)
to put spaces between the data
items;str.ljust
to pad the left "column" with spaces, keeping it the same width; and str.format
to put the padded left column and the header around the ": "
.You can then adapt this to write to your output file (which you could pass as an argument) rather than print
the data, e.g.:
def write_row(out, data, header, col=20):
out.write(...)
and call
write_row(out, (datGroup,), "Space Group")
Upvotes: 2