蟒蛇:从字符串共性 [英] Python: Get common characters from strings

查看:124
本文介绍了蟒蛇:从字符串共性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,newbious问题:我在寻找比较两个字符串,并能够回来,作为单独字符串的最小(和最好)的方式:

So, a newbious question: I'm looking for the smallest (and nicest) way of comparing two strings and being able to get back, as separate strings:


  • 所有常用的字符,

  • 的罕见字符(所有字符但没有常见的)

  • 人物所特有的一根弦。

...使用Python(或Perl,如果是比较容易,但是preferably的Python)。例如:

...using Python, (or Perl, if it's easier—but preferably Python). Example:

A = "123 ABC"
B = "135 AZ"

thingamajigger(A, B) would give all these:

intersect = "13 A" (inclues 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.

(和一个巨大的奖金的人谁可以找到一种方式,将返回所有常见/不常见的字符从任意数量的字符串作为输入的。这将是的确非常方便。)

(And a massive bonus to anyone who can find a way that will return all common/uncommon chars from any number of strings as input. That would be very handy indeed.)

无论如何,感谢大家!

推荐答案

使用 设置

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆