[英]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. x 是我的字符串,l 是我的列表。 (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. (在我的列表中有'空格',所以我需要用'nothing'替换任何错误的字符)但是我的代码不起作用,因为它返回原始的len(x)而不是新的。 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
.正如@Jahnavi Sananse 指出的那样,您应该使用.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))
您的第二次尝试几乎是正确的,但是您需要x = "".join(list(x).remove(i))
而不是list(x).remove(i)
).remove(i)
.join
puts the string right before the point between every element of a list and saves that in a new string. .join
将字符串放在列表的每个元素之间的点之前,并将其保存在新字符串中。
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.如果要计算字符串中的字符,可以使用 .count() 方法完成。 Here I create a dictionary with the count of each letter tested.在这里,我创建了一个字典,其中包含测试的每个字母的计数。
count = {c:x.count(c) for c in l}
s = 'abc12321cba' s = 'abc12321cba'
print(s.replace('a', ''))打印(s.replace('a', ''))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.