简体   繁体   中英

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

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 ?

This has nothing to do with python3 -c or semicolons or backslashes, actually. Your problem is that you're printing a list of strings, ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM