简体   繁体   中英

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)

As @Jahnavi Sananse pointed out you should use .replace .

But to understand why your code isn't working, you need to know that strings are immutable. Your second try was almost right, but instead of list(x).remove(i) you would need x = "".join(list(x).remove(i))

.join puts the string right before the point between every element of a list and saves that in a new string.

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}
  1. We can use string replace() function to replace a character with a new character.
  2. If we provide an empty string as the second argument, then the character will get removed from the string.

s = 'abc12321cba'

print(s.replace('a', ''))

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