[英]Get common characters from 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
方式可以實現它,那么我就開放了。
for i in B:
A = A.replace(i, "")
這有點像對字符串的布爾運算。
使用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)
String1="xyzabc" #String
String2="pqrstuv" #Another String
String1set=set(String1) #need to convert it into set.
String2set=set(String2)
String3=String1set^String2set # ^ for uncommon values
String3=String1set&String2set # & for common values
print(String3)
原因,我們為什么使用,在這里設置-> https://www.python-course.eu/sets_frozensets.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.