0

Can't understand the bold line of code in python: data = "{:^13} {:<11} {:<6}\n" I know there is a string but what's the meaning of the symbold "{}" "^" "<" in this string?The code is from here:

#Run this prior to starting the excercise from random import randint as rnd

memReg = 'members.txt'
exReg = 'inactive.txt'
fee =('yes','no')

def genFiles(current,old):
    with open(current,'w+') as writefile: 
        writefile.write('Membership No  Date Joined  Active  \n')
        **data = "{:^13}  {:<11}  {:<6}\n"**

        for rowno in range(20):
            date = str(rnd(2015,2020))+ '-' + str(rnd(1,12))+'-'+str(rnd(1,25))
            writefile.write(data.format(rnd(10000,99999),date,fee[rnd(0,1)]))


    with open(old,'w+') as writefile: 
        writefile.write('Membership No  Date Joined  Active  \n')
        data = "{:^13}  {:<11}  {:<6}\n"
        for rowno in range(3):
            date = str(rnd(2015,2020))+ '-' + str(rnd(1,12))+'-'+str(rnd(1,25))
            writefile.write(data.format(rnd(10000,99999),date,fee[1]))


genFiles(memReg,exReg)
  • 2
    Those are formatting instructions. See [Format Specification Mini-Language](https://docs.python.org/3/library/string.html#formatspec) – Mike Scotty Jul 17 '22 at 01:15

1 Answers1

0

Here is simple example:

line_to_format = "|{var1:^13}|{var2:<11}|{:<6}|"
line_to_format.format("123", var1="abc", var2="def")

and output:

'|     abc     |def        |123   |'

: - marks the end of former (variable name/variable position) and the start of the format_spec

In this example three types of format_spec:

  • ^13 - fill 13 characters in total and align variable value by center
  • <11 - fill 11 characters in total and align variable value by left
  • <6 - same as above but fill only 6 characters

If variable name is not set (e.g {:<6}) only positional arguments may be used:

line_to_format = "|{:^13}|{:<11}|{:<6}|"
line_to_format.format("123", var1="abc", var2="def")

# error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Replacement index 1 out of range for positional args tuple

line_to_format.format("123", "abc", "def")

# correct output
'|     123     |abc        |def   |'
rzlvmp
  • 7,512
  • 5
  • 16
  • 45