简体   繁体   English

如何获取python中2个字符串之间的公共有序字符?

[英]How to get the common ordered characters between 2 strings in python?

How to get the common ordered characters between 2 strings in python?如何获取python中2个字符串之间的公共有序字符?

for example:例如:

str1 = 'AAA'
str2 = 'AXA'

output should be 'AA' output 应该是'AA'

Compare each characters from 2 strings and keep it when they are the same:比较 2 个字符串中的每个字符,并在它们相同时保留它:

str1 = 'AAA'
str2 = 'AXA'

str3 = ''.join(c1 for c1, c2 in zip(str1, str2) if c1 == c2)
print(str3)

# Output
'AA'

Other example:其他例子:

str1 = 'ABC'
str2 = 'AZB'

str3 = ''.join(c1 for c1, c2 in zip(str1, str2) if c1 == c2)
print(str3)

# Output
'A'

Try like this像这样尝试

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM