I am confused to why textwrap.dedent doesn't work when the details variable contains \n or newlines but it works if there are none. Is there a workaround to make this work?
from textwrap import dedent
log_msg = {
'log_id': 'testid',
'log_level': 'CRITICAL',
'message': 'Complete export to no_cat_products.csv',
'details': 'asdasdasdasdasdasd\n[asdasdasdasdasd\nasdasdasd\n',
'source_application': 'testing.py',
'timestamp': 123445657
}
message = dedent(f"""
ID: {log_msg['log_id']}
Log Level: {log_msg['log_level']}
Message: {log_msg['message']}
Details:
{dedent(log_msg['details'])}
Source Application: {log_msg['source_application']}
Created: {log_msg['timestamp']}
""")
print(message)
Output
ID: testid
Log Level: CRITICAL
Message: Complete export to no_cat_products.csv
Details:
asdasdasdasdasdasd
[asdasdasdasdasd
asdasdasd
Source Application: testing.py
Created: 123445657
You can use lstrip on each line split by '\n'
print('\n'.join([m.lstrip() for m in message.split('\n')]))
textwrap.dedent removes indentation common to all non-blank lines of its input. It doesn't just remove all indentation completely.
Your string contains non-blank lines with no indentation whatsoever, because log_msg['details'] is several lines long. There is no indentation common to all the non-blank lines.
The right way to fix this depends on exactly what you were trying to do in the first place.
log_msg['details'] string, then dedent is the wrong tool - perhaps you should split the string by lines, lstrip every line, and put them back together.dedent call, then maybe you need to build your string differently.str.format instead of f-strings and apply dedent before formatting.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With