简体   繁体   中英

python: printing colored string not working properly

I have simple python script to read file and print it line by line, where comments (lines starting with # ) are printed in color

cat file.txt
# asdf
1234

my python code:

for ln in file
    if COMMENT.match(ln):
        print "%s%s%s" % ('\033[01;32m', ln, '\033[0m'),
    else:
        print ln,

now, strangely, while the regex matching and coloring itself works fine, the print behaves in a way, I cannot explain. This is what gets printed:

# asdf
 1234

The first line is printed green, but notice the one extra space character on the next line, added in front of 1234 . This extra space is added every time, when previous line was colored.

Where is this extra space coming from, and how can i get rid of it ?

For completeness, here is my re.compile expresssion which I am using in the snippet. But that seems to be working fine.

COMMENT = re.compile(r'^#.*$')

As a side note:

Have I chosen the right approach for coloring line. Or is there a better way doing it?

Your line includes a newline character, but you use print with a , to prevent print from adding an extra newline. However, the , adds a space instead, so in the end you print line\\n<space> each time, inserting a space before the next.

Instead of using , , remove the newline from ln and have print add one:

for ln in file:
    ln = ln.rstrip('\n')
    if COMMENT.match(ln):
        print "%s%s%s" % ('\033[01;32m', ln, '\033[0m')
    else:
        print ln

for this simple job, no need to use regex . you can use str.startswith

try this:

with open("yourFile") as file:
    for line in file:
        line = line.rstrip("\n")
        if line.startswith("#"):
            print "%s%s%s" % ('\033[01;32m', line, '\033[0m')
        else:
             print line

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