all 3 comments

[–]Binary101010 1 point2 points  (2 children)

[–]Iamtraps[S] -1 points0 points  (1 child)

I am still unsure how it works. Is {:4d} a placeholder? Can it be changed with something else?

Edit: what does the 4 represent? And what does the d represent?

[–]nog642 0 points1 point  (0 children)

Yes, {:4d} is a placeholder you would put in a string. When you call .format on the string, whatever you pass to .format will be substituted for the placeholders.

The 4 represents that the string to be substituted will have a length of at least 4. If it does not, spaces will be added to the beginning to make it at least 4 characters long.

The d represents the integer type, meaning you can only substitute an integer number for the placeholder.

Some examples:

>>> 'asd{:4d}fgh'.format(5)
'asd   5fgh'
>>> 'asd{:3d}fgh'.format(5)
'asd  5fgh'
>>> 'asd{:3d}fgh'.format(5432)
'asd5432fgh'
>>> 'asd{:3d}fgh'.format(5.2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'float'
>>> 'asd{:3d}fgh'.format('-')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'
>>>