Reputation: 316
So i have a code in which i need to write to file something like this.
def f():
f.write(anothervar)
f.write("\t \t \t \t <------------------ Written from function f ")
f.write('\n')
def g
f():
f.write(somevar)
f.write("\t \t \t \t <------------------ Written from function g ")
f.write('\n')
However when displaying the text file it appears something like this (the code is snipped)
HELLO WORLD <------------------ Written from function g
HELLO WORLD MORE BIG BIGGER <------------------ Written from function f
HELLO WORLD BIGGEST HAHAHAHAHAHAHAHAHHA <------------------ Written from function f
I want every <--- written from function g/h
to be written exact right. How can i do that? From my thinking i can measure length of each line after being written hello world and subtract and do the math however its seems hard and i dont know any function that measure chr in lines. I need short and simple code.
Upvotes: 0
Views: 317
Reputation: 13061
You can get the string length to get how many space insert, or use srt.rjust.
def adjust(string, function):
left, right = 20, 40
tag = '<'+'-'*(15-len(function))+' write from function ' + function
print(string.ljust(left, ' ') + tag.rjust(right, ' '))
text = ['Good Morning !', 'Are you ready', 'How about', 'Test']
func = ['get', 'get', 'post', 'delete']
for t, f in zip(text, func):
adjust(t, f)
Good Morning ! <------------ write from function get
Are you ready <------------ write from function get
How about <----------- write from function post
Test <--------- write from function delete
Upvotes: 1
Reputation: 26
Using format() you can adjust the length of the text you insert
w1 = "This is some text"
w2 = "This is longer text"
w3 = "this is an even longer text "
f.writelines("{:<40} - <----------- Written from w1\n".format(w1))
f.writelines("{:<40} - <----------- Written from w2\n".format(w2))
f.writelines("{:<40} - <----------- Written from w3\n".format(w3))
This is some text - <----------- Written from w1
This is longer text - <----------- Written from w2
This is an even longer text - <----------- Written from w3
Upvotes: 1