I have a function that uses pformat()
to convert a dictionary to a string (irrelevant: string will be later inserted with write()
in a .py
file).
So MY_DCT = {1: 11, 2: 22, 3: 33}
would become a string like this:
MY_DCT = {
1: 11,
2: 22,
3: 33}
There are 2 requirements for the function:
- Dict items must be displayed after the first line.
- Elements have to be indented by 4 whitespaces.
Here is the function:
import pprint
def f(obj_name, obj_body_as_dct):
body = '{\n' + pprint.pformat(obj_body_as_dct, indent=4, width=1)[1:]
name_and_equal_sign = obj_name + ' = '
return name_and_equal_sign + body + '\n\n'
d = {1: 11, 2: 22, 3: 33}
print(f('MY_DCT', d))
If indent=0
i get this string:
MY_DCT = {
1: 11,
2: 22,
3: 33}
If indent=4
i get this string:
MY_DCT = {
1: 11,
2: 22,
3: 33}
I checked the parameters of pformat()
but i couldn't figure out how to make the correct number of whitespaces appear on each line.
I know i can use replace()
, +' '
etc., to fix the string, but i m wondering where does that extra whitespace come from and if i can get rid of it by setting correctly the parameters (if that is even possible, that is).
Note: If there is a better way to achieve the above, do let me know.
print(pp.pformat({1:11, 2:22, 3:33}, indent=0, width=1))
, withindent
going from 0 to 2. You ll notice, it applies one less whitespace on the first line. It is the waypformat()
is built. – Octagonal