Iterating over a dictionary in python and stripping white space

后端 未结 7 591
佛祖请我去吃肉
佛祖请我去吃肉 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:35

    I use the following. You can pass any object as an argument, including a string, list or dictionary.

    # strip any type of object
    def strip_all(x):
      if isinstance(x, str): # if using python2 replace str with basestring to include unicode type
        x = x.strip()
      elif isinstance(x, list):
        x = [strip_all(v) for v in x]
      elif isinstance(x, dict):
        for k, v in x.iteritems():
          x.pop(k)  # also strip keys
          x[ strip_all(k) ] = strip_all(v)
      return x
    

提交回复
热议问题