Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do empty curly braces mean in a string?

Tags:

python

So I have been browsing through online sites to read a file line by line and I come to this part of this code:

print("Line {}: {}".format(linecount, line))

I am quite confused as to what is happening here. I know that it is printing something, but it shows:

"Line{}"

I do not understand what this means. I know that you could write this:

foo = "hi"
print(f"{foo} bob")

But I don't get why there are empty brackets.

like image 483
noobie Avatar asked Sep 11 '25 12:09

noobie


1 Answers

Empty braces are equivalent to numeric braces numbered from 0:

>>> '{}: {}'.format(1,2)
'1: 2'
>>> '{0}: {1}'.format(1,2)
'1: 2'

Just a shortcut.

But if you use numerals you can control the order:

>>> '{1}: {0}'.format(1,2)
'2: 1'

Or the number of times something is used:

>>> '{0}: {0}, {1}: {1}'.format(1,2)
'1: 1, 2: 2'

Which you cannot do with empty braces.

like image 169
dawg Avatar answered Sep 13 '25 01:09

dawg