Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write for loop with condition in one line

Here is the original code:

import site; 
import re 

for i in site.getsitepackages():
    package = re.search("^/usr/local/lib/.*/dist-packages$", i)
    if package is None:
        continue
    print(package.string)

Output:

/usr/local/lib/python3.8/dist-packages

Here is the one line code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import site; import re; for i in site.getsitepackages(): package = re.search("^/usr/local/lib/.*/dist-packages$", i); if package is None: continue; print(package.string)

Output:

  File "/tmp/ipykernel_2984/3719293883.py", line 1
    import site; import re; for i in site.getsitepackages(): package = re.search("^/usr/local/lib/.*/dist-packages$", i); if package is None: continue; print(package.string)
                            ^
SyntaxError: invalid syntax

I want to convert the above multiple lines into one line, and then run it in the bash command line:

python3 -c "<one line python code>"

>Solution :

Why a single line? It will impact readability.

Just use a heredoc:

python3 <<!
import site;
import re

for i in site.getsitepackages():
     package = re.search("^/usr/local/lib/.*/dist-packages$", i)
     if package is None:
         continue
     print(package.string)
!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading