簡體   English   中英

從字符串中獲取常用字符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM