Reputation: 67
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.
Upvotes: 4
Views: 3981
Reputation: 103764
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.
Upvotes: 4
Reputation: 4200
Doing "My {} string is {}".format('formatted', 'awesome')
just fills in the curly braces with the args you provide in the format function in the order you enter the arguments.
So the first {}
in the above string would get 'formatted'
and the second in that case would get 'awesome'
.
It's an older version of formatting strings than f strings (which I'm glad I started learning Python when these already came out), but you can equally write something like this similar to f-strings:
>>> template = 'I love {item}. It makes me {emotion}'
>>>
>>> my_sentence = template.format(item='fire', emotion='calm')
>>> print(my_sentence)
I love fire. It makes me calm.
Upvotes: 2
Reputation: 172
This is a different way to interpolate strings in Python.
Docs: https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting
The usage of string interpolations like this f'Results of the {year} {event}'
came in Python 3.6.
Upvotes: 1