After inputting a string such as: '3,11,15,16,35'
if you wanted each number to represent the line-number of some code,
for the purpose of adding a comment to those lines,
what would you do?
More specifically, in a for-loop where you iterate over each line of code, how would you check the string to see if it contains the current line number.
Here’s there relevant section of what I tried:
self.num = input('Line(s) to number?')
self.linelist = self.code.splitlines()
for i, element in enumerate(self.linelist):
self.count += 1
# if match(str(self.count) + r",", self.num):
if self.num.find(str(self.count) + ','):
self.final = self.final + element + ' # line ' + str(self.count) + '\n'
else:
self.final = self.final + element + '\n'
The re.match attempt only comments the first line-number in the string.
The find attempt seems to match the first,
but comments everything other than the line associated with that number.
The other issue with this setup is that 1, could be found if 11, was in the list.
Problem is, you are using the result of
finddirectly in anifstatement. Just look at whatfindreturns:So, you will be getting an
integercorresponding the index of first match or-1. When you doif an_integer:, it is actually doingif bool(an_integer):.bool(an_integer)isFalseforan_integer==0andTruefor everything else. That means you’ll be doingelsepart if your line number is found at the beginning of the input andifpart for everything else. You’ll need to do something like:to denote a match.
As for the
re.matchpart,re.matchtries to match a substring from the beginning of the string. You should usere.searchinstead.That being said, even with these fixes and even with the delimiter you’ll still have the problem of mismatch as you identified.
11,will match both1,and11,. To solve this, you can split the input with delimiter and obtain a list of values. Then you can check if the value is in that list:As a small side note, you are already using
enumerateto get the line numbers. That should eliminate the use of counter (i.e.self.count). If you want them to start from1, you can tellenumerateto do so by giving the optional second argument:Then, use
iinstead ofself.count.