Search code examples
pythonliststring-length

Deleting characters from a string in Python


I have a list of characters. I would like to count that how many characters are in a string which are also in the list. x is my string and l is my list. (in my list there is 'space' so I need to replace any wrong characters with 'nothing') But my code does not work, because it gives back the original len(x) and not the new. Can you help me correct my code?

x = 'thisQ Qis'
l = ['t', 'h', 'i', 's']

for i in x:
    if i not in l:
        i =''
print(len(x))

#or

for i in x:
    if i not in l:
       list(x).remove(i)
print(len(x))

for i in x:
    if i not in l:
        x.replace("i", '')
print(x)

Solution

  • If you want to keep all the characters in one list but not the other, then something like this works:

    x     = 'thisQ Qis'
    l     = 'tihs '     #A string is already a list of characters. 
    new_x = ''.join(c for c in x if c in l)
    

    If you want to count the characters in a string that can be done with the .count() method. Here I create a dictionary with the count of each letter tested.

    count = {c:x.count(c) for c in l}