Home > other >  String intersection by removing invalid character in python
String intersection by removing invalid character in python

Time:03-09

Given the following code:

word1 = '121#2#1'
word2 = '7#3#271'
    
list1 = [i for i, ltr in enumerate(word1) if ltr == '#']
list2 = [i for i, ltr in enumerate(word2) if ltr == '#']
result = list(set(list1) | set(list2))
# result = [1,3,5]

How could I remove word1 and word2 characters from the index positions indicated in the result list.

In other words, I would like to obtain the following result:

word1 = '1121'
word2 = '7321'

Thanks for your attention!

CodePudding user response:

Here, as suggested in the comment, do a regular loop and check that in the current position both words have a character different than #

word1 = '121#2#1'
word2 = '7#3#271'
result1 = ''
result2 = ''
for i in range(len(word1)):
    if word1[i] != '#' and word2[i] != '#':
        result1  = word1[i]    
        result2  = word2[i]

You can also use zip if you feel like iterating over indexes is not pythonic enough

word1 = '121#2#1'
word2 = '7#3#271'
result1 = ''
result2 = ''
for a,b in zip(word1, word2):
    if a != '#' and b != '#':
        result1  = a
        result2  = b
  • Related