How to print a newline when running 'python -c'

Question:

The following prints the 2-characters and n between each item in the list instead of a newline.

python3 -c 'import airflow.operators as air_ops;  
    print([f"""{k}: {v}n""" for k,v in air_ops.__dict__.items()])'

How can we get the desired escape character/newline when running python -c ?

Asked By: WestCoastProjects

||

Answers:

This has nothing to do with python3 -c or semicolons or backslashes, actually. Your problem is that you’re printing a list of strings, i.e. the for-loop is inside the list comprehension. String elements inside of a list will always be represented using their repr, which means newline characters will be escaped.

Instead, just use a loop. Literal newlines are fine for python3 -c. Let the print function append the trailing new line. You can leave out all the semicolons and backslashes.

$ python3 -c 'd = {"k1": "v1", "k2": "v2"}
> for k, v in d.items():
>     print(f"{k}: {v}")
> '
k1: v1
k2: v2
Answered By: wim
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.