简体   繁体   中英

Python: will not find a string in a list even though it definitely is there

This should be such a simple issue but it's driving me nuts. When I search for the keyword 'gift' in a list of strings, python will find it as long as I manually set the string 'gift'. When I derive the string from a dictionary key, python will not find it in the list in question even though the dict key is an identical string object with no typos. Here's the exact code:

This WORKS:

subtopic_keys = list(copy.deepcopy(subtopic_map).keys())

for element in subtopic_keys: 
    try:
        for dict_object in subtopic_map[element]:
            for key2 in dict_object.keys():
                for index, entry in enumerate(dict_object[key2]['tweets']):
                    count = 0
                    if 'gift' in clean(entry).split():
                        pass
                    if 'gift' not in clean(entry).split():
                        dict_object[key2]['tweets'][index] = 'removed'
    except KeyError:
        pass

This does NOT work. Note: the only change is 'gift' has been replaced by element from the first for loop, which is an identical string object. I verified this by printing type(element) and it is of the string class.

subtopic_keys = list(copy.deepcopy(subtopic_map).keys())

for element in subtopic_keys: 
    try:
        for dict_object in subtopic_map[element]:
            for key2 in dict_object.keys():
                for index, entry in enumerate(dict_object[key2]['tweets']):
                    count = 0
                    if element in clean(entry).split():
                        pass
                    if element not in clean(entry).split():
                        dict_object[key2]['tweets'][index] = 'removed'
    except KeyError:
        pass

The last bit of code replaces every entry with 'removed', implying python does not recognize the string in any entry, so long as it's derived from a dict key. Why would that be the case? The dict key is an identical string class object.

I had the same problem. Turns out my list had "\\n" at the end of all the element strings. This is how i worked it out.

openList=open("list.txt","r")
list = b.readlines() # this returned \n in each element of the list
list2=[x.replace("\n","") for x in list] #this removes all the \n in all elements in list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM