How to search for a substrings value inside of a string?
Question: I am trying to find the value of a property, inside of a string. In `<img
src="invalidURL.com">` if the property/sub-string were to be `src`, I would
want to recieve `invalidURL.com`.

In Violent Python it uses the line `imgSrc = imgTag['src']`, which does not
givee a compiler error, and the script runs fine. (Full script can be found in
[this Github repo.](https://github.com/shadow-box/Violent-Python-
Examples/blob/master/Chapter-3/4-exifFetch.py)) However, when I tried to write
my own script it gives a compiler error.

    
    
    htmlImgTags = ['<img src="/images/icons/product/chrome-48.png"/>', '<img src="asdasd">']
    for tag in htmlImgTags:
        print tag
        tagSrc = tag['src'] 
        print tagSrc
    

The error complains about using a string as an index instead of an int.

    
    
    <img src="/images/icons/product/chrome-48.png"/>
    Traceback (most recent call last):
      File "looking in an array.py", line 4, in <module>
        tagSrc = tag['src'] 
    TypeError: string indices must be integers, not str
    

What exactly is going wrong in my code, but not in the book's?


Answer: The code you link to appears to be using a library called [Beautiful
Soup](http://www.crummy.com/software/BeautifulSoup/) to parse the HTML. That
loop is over a list of tag objects created by Beautiful Soup, not a list of
the actual tag text.

Here's an example using [Beautiful Soup
v3](http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html):

    
    
    from BeautifulSoup import BeautifulSoup
    
    html_doc = """
    <img src="/images/icons/product/chrome-48.png"/>
    <img src="/images/icons/product/chrome-49.png"/>
    """
    
    soup = BeautifulSoup(html_doc)
    html_img_tags = soup.findAll("img")
    
    for tag in html_img_tags:
      print tag['src']
    

The output is:

    
    
    /images/icons/product/chrome-48.png
    /images/icons/product/chrome-49.png
    

Note that `tag` is **not** just a string, it's a BeautifulSoup tag object:

    
    
    >>> type(html_img_tags[0])
    <class 'BeautifulSoup.Tag'>
    

If you print it, it will display as a nicely formatted tag:

    
    
    >>> print html_img_tags[0]
    <img src="/images/icons/product/chrome-48.png" />
    

But that's only because BeautifulSoup makes sure that the object converts
itself to that string for easy inspection.

* * *

Note: if you happen to have BS4 on your machine instead, the import line
should be:

    
    
    from bs4 import BeautifulSoup
    

...and the `findAll()` function is now `find_all()`.

