0

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.

Machine Yadav
  • 196
  • 3
  • 13

2 Answers2

1

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
Jason Yang
  • 11,284
  • 2
  • 9
  • 23
1

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
UweB
  • 26
  • 4
  • Thanks @UweB. Good. What is :<40 can you explain and give some links. – Machine Yadav Jun 17 '20 at 11:13
  • The curly brackets and content are used by the string format() method. :<40 means to format the content (.format(w1)) left adjusted and a length of 40 characters. You find a detailed description at [https://docs.python.org/3/tutorial/inputoutput.html] – UweB Jun 17 '20 at 17:49