[英]How to get the common ordered characters between 2 strings in python?
如何獲取python中2個字符串之間的公共有序字符?
例如:
str1 = 'AAA'
str2 = 'AXA'
output 應該是'AA'
比較 2 個字符串中的每個字符,並在它們相同時保留它:
str1 = 'AAA'
str2 = 'AXA'
str3 = ''.join(c1 for c1, c2 in zip(str1, str2) if c1 == c2)
print(str3)
# Output
'AA'
其他例子:
str1 = 'ABC'
str2 = 'AZB'
str3 = ''.join(c1 for c1, c2 in zip(str1, str2) if c1 == c2)
print(str3)
# Output
'A'
像這樣嘗試
result = ''
for i in range(0, len(str1)):
if str1[i] == str2[i]:
result += str1[i]
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.