简体   繁体   中英

Python: removing everything including and after a certain character on a line

I have some text like so:

1.6 # blah blah blah
# fjsadfklj slkjf yes 3.4
1.8*
1.9 1.10 #blah
#blah
1.11

I want to clean it up by removing all # characters plus anything following them on the same line. In other words, I desire:

1.6
1.8*
1.9 1.10
1.11

What is the best way to approach this? Via simple methods like partition , or maybe regexes?

Maybe this does what you want it to do in fulfilling your request?

example = '''1.6 # blah blah blah
# fjsadfklj slkjf yes 3.4
1.8*
1.9 1.10 #blah
#blah
1.11'''

for line in example.splitlines():
    print(line.split('#', 1)[0])

If you really want the comment text, the code is easily modifiable to allows its capture as well.

You may try this,

re.sub(r'\s*#.*', '', s)

\\s* will helps to match also the preceding vertical or horizontal space character. What I mean by vertical space is newline character , carriage return.

DEMO

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