📜  Python – 删除字符串中相似的索引元素

📅  最后修改于: 2022-05-13 01:54:18.410000             🧑  作者: Mango

Python – 删除字符串中相似的索引元素

给定两个字符串,从两者中删除所有在相似索引处相同的元素。

方法 #1:使用循环 + zip() + join()

在此,我们使用 join() 将元素与其索引配对,并检查不等式以仅过滤两个字符串中的不同元素, join() 用于将结果转换为字符串。

Python3
# Python3 code to demonstrate working of 
# Remove similar index elements in Strings
# Using join() + zip() + loop
  
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# conversion to list for zipping
list1 = list(test_str1)
list2 = list(test_str2)
res1 = []
res2 = []
for ch1, ch2 in zip(list1, list2):
      
    # check inequalities
    if ch1 != ch2:
        res1.append(ch1)
        res2.append(ch2)
  
# conversion to string 
res1 = "".join(res1)
res2 = "".join(res2)
      
# printing result 
print("Modified String 1 : " + str(res1)) 
print("Modified String 2 : " + str(res2))


Python3
# Python3 code to demonstrate working of 
# Remove similar index elements in Strings
# Using list comprehension
  
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# one-liner to solve problem
res = ["".join(mastr) for mastr
      in zip(*[(a, b) for a, b in zip(test_str1, test_str2) if a != b])]
  
# printing result 
print("Modified String 1 : " + str(res[0])) 
print("Modified String 2 : " + str(res[1]))


输出
The original string 1 is : geeks
The original string 2 is : beaks
Modified String 1 : ge
Modified String 2 : ba

方法#2:使用列表推导

使用与上述类似的方法执行任务,只需一行以紧凑的形式执行任务。

Python3

# Python3 code to demonstrate working of 
# Remove similar index elements in Strings
# Using list comprehension
  
# initializing strings
test_str1 = 'geeks'
test_str2 = 'beaks'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# one-liner to solve problem
res = ["".join(mastr) for mastr
      in zip(*[(a, b) for a, b in zip(test_str1, test_str2) if a != b])]
  
# printing result 
print("Modified String 1 : " + str(res[0])) 
print("Modified String 2 : " + str(res[1])) 
输出
The original string 1 is : geeks
The original string 2 is : beaks
Modified String 1 : ge
Modified String 2 : ba