简体   繁体   中英

Can someone please explain what is this line of code?

I want to know what does this {:<15}{} mean?

def printResults(swimmers,timings):
        fmt = '{:<15}{}'
        for i in range(len(swimmers)):
            print(fmt.format(swimmers[i],timings[i]))
        
        print("The fastest timing is {}s".format(min(timings)))
         

This is string formatting syntax. You can read about string formatting in:

  1. https://www.programiz.com/python-programming/methods/string/format
  2. https://pyformat.info/
  3. https://www.w3schools.com/python/ref_string_format.asp

The format() method formats the specified value(s) and insert them inside the string's placeholder.

The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.

The format() method returns the formatted string.

In your specific case: {:<15}{} :

The first {:<15} will insert the value in swimmers[i] with leading white spaces. The second {} will insert the value in timings[i] as is.

If the length of swimmers[i] is less than 15 it will add white spaces so the length of swimmers[i] plus the added white spaces is 15 (try it will lower number, eg '{:<5}{}' to see how it works). If the length of swimmers[i] is more than 15, no white spaces will be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM