Search code examples
pythonlistcounterfindall

Common character search can't find usages of "?" in list


I'm counting the characters in string and which are used commonly between each word in the list, for some reason it causes an error when a character like "?" is thrown into a word or as it's own string. I have two seperate ways of doing it the counter seems to identify the "?" but the other doesn't for some reason? Thanks for the help in advance I'm sure it's something I'm missing but I can't understand why it is giving me the error for one and not the other.

I would hope to use the second method to do it and not the Counter way if possible

Name = ["Adam","Max","Mike","Ted","Liam","Daniel"]


#You can see that the above list will work with both methods but for some reason adding a "?" to either causes issues and errors
def listToString(s):
        str1 = " "

        return (str1.join(s))
s = Name
stringOfList =(listToString(s))




from collections import Counter

s1 = stringOfList.lower()

commonLetters = Counter(s1)
print(commonLetters)








import re


test1 = s1
test2 = test1

common = {}

if len(test1) < len(test2):
        for character in test1:
                if character in test2:
                        common[character] = len(re.findall(character, test2))

else:
        for character in test2:
                if character in test1:
                        common[character] = len(re.findall(character, test1))
for word, count in common.items():
        print("\nThe words contains these common characters" +" {1}\t{0}".format(word,count))

Solution

  • Try something more like this.

    
    from collections import Counter
    Name = ["Adam","Max","Mike","Ted","Liam","Daniel?"]
    stringOfList = ' '.join(Name)
    s1 = stringOfList.lower()
    commonLetters = Counter(s1)
    for letters in commonLetters:
        print(f"letters count of {letters} is {commonLetters[letters]}")