Iterating over a dictionary in python and stripping white space

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

    Although @zquare had the best answer for this question, I feel I need to chime in with a Pythonic method that will also account for dictionary values that are not strings. This is not recursive mind you, as it only works with one dimensional dictionary objects.

    d.update({k: v.lstrip() for k, v in d.items() if isinstance(v, str) and v.startswith(' ')})
    

    This updates the original dictionary value if the value is a string and starts with a space.

    UPDATE: If you want to use Regular Expressions and avoid using starts with and endswith. You can use this:

    import re
    rex = re.compile(r'^\s|\s$')
    d.update({k: v.strip() for k, v in d.items() if isinstance(v, str) and rex.search(v)})
    

    This version strips if the value has a leading or trailing white space character.

提交回复
热议问题