从字符串中获取常见字符 [英] Get common characters from strings
本文介绍了从字符串中获取常见字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找比较两个字符串并能够作为单独的字符串取回的方式:
I'm looking for the way of comparing two strings and being able to get back, as separate strings:
- 所有常见字符,
- 不常见的字符,(所有字符,但没有常见的字符)
- 一个字符串唯一的字符.
示例:
A = "123 ABC"
B = "135 AZ"
thingamajigger(A, B) # would give all these:
intersect = "13 A" # (includes space)
exclusion = "2BCZ5"
a_minus_b = "2BC"
b_minus_a = "5Z"
a_minus_b
非常简单...但是,如果有一种花哨的单线方式将其拉开,那么我很开放.
a_minus_b
is quite simple... but if there's one of those fancy one-liner ways to pull it off, then I'm open.
for i in B:
A = A.replace(i, "")
这有点像对字符串的布尔操作.
It's a bit like boolean operations on strings.
推荐答案
使用 set
:
s = set("123 ABC")
t = set("135 AZ")
intersect = s & t # or s.intersection(t)
exclusion = s ^ t # or s.symmetric_difference(t)
a_minus_b = s - t # or s.difference(t)
b_minus_a = t - s # or t.difference(s)
这篇关于从字符串中获取常见字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文