Iterating over a dictionary in python and stripping white space

后端 未结 7 545
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 01:10

I am working with the web scraping framework Scrapy and I am a bit of a noob when it comes to python. So I am wondering how do I iterate over all of the scraped items which

7条回答
  •  暖寄归人
    2021-01-13 01:31

    What you should note is that lstrip() returns a copy of the string rather than modify the object. To actually update your dictionary, you'll need to assign the stripped value back to the item.

    For example:

    for k, v in your_dict.iteritems():
        your_dict[k] = v.lstrip()
    

    Note the use of .iteritems() which returns an iterator instead of a list of key value pairs. This makes it somewhat more efficient.

    I should add that in Python3, .item() has been changed to return "views" and so .iteritems() would not be required.

提交回复
热议问题