我有一个类似'LETTER'的字符串现在我有另一个字符串“LTR”当用前一个字符串检查字符串时剩余的字母是“ETE”我怎么能从python中的主字符串中提取它。字母的顺序无关紧要我们应该得到剩余的字母
答案 0 :(得分:2)
使用difflib
库中的ndiff()
:
>>> from difflib import *
>>> list(ndiff("LETTER","LTR"))
[' L', '- E', ' T', '- T', '- E', ' R']
#so filter out letters which doesn't have '-'
>>> ''.join(x.strip('-').strip() for x in filter(lambda x:'-' in x,ndiff("LETTER","LTR")))
'ETE'
>>> ''.join(x.strip('-').strip() for x in filter(lambda x:'-' in x,ndiff("stack","tc")))
'sak'
你可以使用Counter()
,如果字母顺序无关紧要:
>>> from collections import Counter
>>> str1="LETTER"
>>> str2="LTR"
>>> c=Counter(str1)-Counter(str2)
>>> c
Counter({'E': 2, 'T': 1})
>>> ''.join(x*c[x] for x in c)
'EET
答案 1 :(得分:2)
热门问题:-)我认为这是一个非常易读的问题:
s=list("LETTER")
p=list("LTR")
while p: s.remove(p.pop())
现在
print("".join(s))
打印“ETE”
答案 2 :(得分:1)
>>> x = "LETTER"
>>> for c in "LTR":
... if c in x:
... p = x.find(c)
... if p < len(x)-1:
... x = x[:p]+x[p+1:]
... else:
... x = x[:p]
...
>>> x
'ETE'
答案 3 :(得分:1)
这是一个相当简单易懂的解决方案,可以正确保留输入字符串的排序和重复:
def omit(s, discard):
discard = list(discard)
for c in s:
if c not in discard:
yield c
else:
discard.remove(c)
>>> ''.join(omit('LETTER', 'LTR'))
'ETE'
答案 4 :(得分:1)
#!/bin/env python
def str_diff(s, rem):
for x in rem:
pos = s.find(x)
if pos >= 0: s = s[:pos] + s[pos+1:]
return s
print str_diff("LETTER", "LTR") # ETE
print str_diff("LETTER", "LTTR") # EE
print str_diff("LETTER", "LTRxyz") # ETE
这似乎可以做你想做的事。它保留了原始排序,适用于“删除集”中相同字母的倍数,如果“删除集”包含不在原始字符串中的字符,则不会禁止。
答案 5 :(得分:1)
>>> x = "LETTER"
>>> r = "LTR"
>>> y = x
>>> for c in r:
... y = y.replace(c, '', 1)
...
>>> y
'ETE'
答案 6 :(得分:0)
def remaining(my_string, my_string_2):
output = ""
i = 0
j = 0
while i < len(my_string) and j < len(my_string_2):
if my_string[i] != my_string_2[j]:
output += my_string[i]
else:
j += 1
i+=1
if i < len(my_string):
output+=my_string[i:len(my_string)]
return output
result = remaining("LETTER", "LTR")
print result
返回'ETE'
答案 7 :(得分:0)
l1='LETTER'
l2='LTR'
occur=[]
for i in range(0,len(l1)):
if l1[i] in occur:
print l1[i]
if l1[i] in l2:
occur.append(l1[i])
else:
print l1[i]