Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I append the index of a string to a list using extend() in python?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading