Python Forum

Full Version: Confused by {} in Python code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.


I downloaded some Python code that has a line of code like this:

print('M = {}'.format(M))

where M is defined like this:

M = ((n - m) * np.log(np.linalg.det(Xp))) \
- (n_1 - 1) * (np.log(np.linalg.det(np.cov(X0)))) - (n_2 - 1) * (np.log(np.linalg.det(np.cov(X1))))

---

I'm confused what's going on with the "{}" inside the 'M = {}'.

What do the braces represent/do in this context?

Thanks very much in advance,

-O
In your code snippet, The {} is a placeholder for formatted text, see: https://docs.python.org/3/tutorial/inputoutput.html
you will also see '{' and '}' as bounds for creating a dictionary.
It is a way to format strings in Python. Similar to using % notation in Python 2, C language etc. So in your case {}  gets substituted with value of M, which is calculated with the formula you provided.

Here you can find documentation on it and a few simple examples:
https://docs.python.org/3.4/library/stri...t-examples
In version 3.6.3 you can also use: print(f"M = {M}")
It's called string formatting.
The evolution of string formatting.
>>> M = 100
>>> # old don't use
>>> print('M = %d' % M)
M = 100
>>> 
>>> # Python 2.6 we get format()
>>> print('M = {}'.format(M))
M = 100
>>> 
>>> # Python 3.6 we get f-string
>>> print(f'M = {M}')
M = 100
f-string is the future,but format() will be used for a long time.
f-string can take expressions here calculate and upper():
>>> a = 10
>>> b = 20
>>> s = 'correct'
>>> print(f'The sum of a {a} and b {b} is {a+b} {s.upper()}')
The sum of a 10 and b 20 is 30 CORRECT
More about format() PyForamt.
(Dec-03-2017, 04:11 PM)snippsat Wrote: [ -> ]More about format() PyFormat.

Nice answer and awesome resource, thanks!
(Dec-03-2017, 04:06 PM)j.crater Wrote: [ -> ]It is a way to format strings in Python. Similar to using % notation in Python 2, C language etc. So in your case {}  gets substituted with value of M, which is calculated with the formula you provided.

Here you can find documentation on it and a few simple examples:
https://docs.python.org/3.4/library/stri...t-examples

Thanks very much!

That was exactly what I needed.

Sorry, I should have RTFM first. :)

- O

(Dec-03-2017, 04:11 PM)snippsat Wrote: [ -> ]It's called string formatting.
The evolution of string formatting.
>>> M = 100
>>> # old don't use
>>> print('M = %d' % M)
M = 100
>>> 
>>> # Python 2.6 we get format()
>>> print('M = {}'.format(M))
M = 100
>>> 
>>> # Python 3.6 we get f-string
>>> print(f'M = {M}')
M = 100
f-string is the future,but format() will be used for a long time.
f-string can take expressions here calculate and upper():
>>> a = 10
>>> b = 20
>>> s = 'correct'
>>> print(f'The sum of a {a} and b {b} is {a+b} {s.upper()}')
The sum of a 10 and b 20 is 30 CORRECT
More about format() PyForamt.


Excellent! I've copied these for reference.

- O