I really want to remove all comments like: #This does this
for example, as I annotated it ages ago, and I want to try and work out what all the parts of the code do, without going through 600+ lines and deleting them individually.
Asked
Active
Viewed 2,283 times
0

Terry Jan Reedy
- 18,414
- 3
- 40
- 52

18166
- 111
- 1
- 13
-
Since IDLE doesn't have a "remove all comments" menu item, I don't think this question really has anything to do with IDLE. You could have equivalently asked "how do I remove comments from a Python script?" without making any mention of the IDE. – Kevin Feb 10 '15 at 15:38
-
In the interpreter, or the editor? You can easily make another program to remove comments. – Malik Brahimi Feb 10 '15 at 15:39
-
Use an editor that supports regex search and replace, e.g. in vim I could naively do `:%s/#.*$//g` [assuming there are no '#'s in string literals]. – AChampion Feb 10 '15 at 15:43
-
oh, what a miracle. Posted an answer for a question which is marked as dupe 25 mins ago. – Avinash Raj Feb 10 '15 at 16:05
-
@MalikBrahimi The editor. Is that not what IDLE is? – 18166 Feb 10 '15 at 17:38
-
Yes, I mean which mode: interactive or scripting. – Malik Brahimi Feb 10 '15 at 17:54
-
@MalikBrahimi The scripting mode. I am still new to programming in general, and I have no idea how to do this without wasting a lot of time deleting each line. – 18166 Feb 10 '15 at 17:56
-
Do you have any hash tags in strings? – Malik Brahimi Feb 10 '15 at 17:58
-
Then use a for loop to iterate through the lines, find a hashtag, and remove everything after. – Malik Brahimi Feb 11 '15 at 16:29
-
@MalikBrahimi That's why I was asking, I don't know how to do that. – 18166 Feb 11 '15 at 16:56
-
Well you'll need to reopen the question so that I can write an answer. – Malik Brahimi Feb 11 '15 at 17:05
1 Answers
0
For this, you could use re module.
>>> s = """foo bar
#This does this
# foo bar
bar foo"""
>>> for i in s.split('\n'):
if not re.match(r'\s*#', i):
print(i)
foo bar
bar foo

Avinash Raj
- 172,303
- 28
- 230
- 274
-
Probably better to use `\s*` before the `#`, in case the OP (or some future visitor) uses tabs. Also, note that this will struggle with e.g. multiline strings *within* the code. – jonrsharpe Feb 10 '15 at 16:18
-
since we are splitting the input according to the `\n` chaarcter, `\s*` at the start won't create any problems. – Avinash Raj Feb 10 '15 at 16:25
-
Thanks for the answer, but this doesn't answer my question - I meant how to remove them in the script editor, which I thought was called IDLE. I will edit my question for this. – 18166 Feb 10 '15 at 17:37