Confused by {} in Python code - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Confused by {} in Python code (/thread-6693.html) |
Confused by {} in Python code - Oliver - Dec-03-2017 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 RE: Confused by {} in Python code - Larz60+ - Dec-03-2017 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. RE: Confused by {} in Python code - j.crater - Dec-03-2017 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/string.html#format-examples RE: Confused by {} in Python code - sparkz_alot - Dec-03-2017 In version 3.6.3 you can also use: print(f"M = {M}")
RE: Confused by {} in Python code - snippsat - Dec-03-2017 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 = 100f-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 CORRECTMore about format() PyForamt. RE: Confused by {} in Python code - j.crater - Dec-03-2017 (Dec-03-2017, 04:11 PM)snippsat Wrote: More about format() PyFormat. Nice answer and awesome resource, thanks! RE: Confused by {} in Python code - Oliver - Dec-03-2017 (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. 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. Excellent! I've copied these for reference. - O |