Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textwrap.dedent not working when there are newlines

Tags:

python

string

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
like image 432
spyware97 Avatar asked Nov 23 '25 03:11

spyware97


2 Answers

You can use lstrip on each line split by '\n'

print('\n'.join([m.lstrip() for m in message.split('\n')]))
like image 135
Teshan Shanuka J Avatar answered Nov 25 '25 18:11

Teshan Shanuka J


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.

  • If you wanted to remove all indentation completely, including indentation that was in the original 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.
  • If you were expecting all lines to have the same leading indentation before the dedent call, then maybe you need to build your string differently.
  • If you wanted your code to behave as if the format string itself had no indentation, then you should write a format string with no indentation, or use str.format instead of f-strings and apply dedent before formatting.
like image 22
user2357112 supports Monica Avatar answered Nov 25 '25 19:11

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!