Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String intersection by removing invalid character in python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

word1 = '1121'
word2 = '7321'

Thanks for your attention!

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading