Reputation: 8748
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.
Upvotes: 0
Views: 178
Reputation: 36715
Problem is, you are using the result of find
directly in an if
statement. Just look at what find
returns:
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
So, you will be getting an integer
corresponding the index of first match or -1
. When you do if an_integer:
, it is actually doing if bool(an_integer):
. bool(an_integer)
is False
for an_integer==0
and True
for everything else. That means you'll be doing else
part if your line number is found at the beginning of the input and if
part for everything else. You'll need to do something like:
if self.num.find(str(self.count) + ',') >= 0:
to denote a match.
As for the re.match
part, re.match
tries to match a substring from the beginning of the string. You should use re.search
instead.
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 both 1,
and 11,
. 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:
self.num = input('Line(s) to number?').split(",")
# ...
if str(self.count) in self.num:
#...
As a small side note, you are already using enumerate
to get the line numbers. That should eliminate the use of counter (i.e. self.count
). If you want them to start from 1
, you can tell enumerate
to do so by giving the optional second argument:
for i, element in enumerate(self.list, 1):
Then, use i
instead of self.count
.
Upvotes: 3