I’m trying to look through a long string to find instances of a substring, then I want to create a list that has the index of each substring found and the substring found. But instead of the index in a readable form, I’m getting a reference to the object, such as [<built-in method index of str object at 0x000001687B01E930>, 'b']
. I’d rather have [123, 'b']
.
Here’s the code I’ve tried:
test_string = "abcdefg"
look_for = ["b","f"]
result = []
for each in test_string:
if each in look_for:
result.extend([each.index, each])
print(result)
I know I could do this with a list comprehension, but I plan to add a bunch of other code to this for
later and am only asking about the index issue here.
I’ve tried str(each.index)
and print(str(result))
But that doesn’t help. What am I missing?
>Solution :
Here are 2 ways you can achieve it, either using .index() or enumerate()
test_string = "abcdefg"
look_for = ["b","f"]
result = []
for i, each in enumerate(test_string):
if each in look_for:
result.append((i, each))
print(result)
result = []
for i in look_for:
try:
result.append((i, test_string.index(i)))
except:
pass
print(result)