Search code examples
python

Python conditional replacement based on element type


In Python 3.7 I am trying to remove pipe characters

r=(('ab|cd', 1, 'ab|cd', 1), ('ab|cd', 1, 'ab|cd', 1))
[[x.replace('|', '') for x in l] for l in r]

Error: 'int' object has no attribute 'replace'

Desired outcome: (('abcd', 1, 'abcd', 1), ('abcd', 1, 'abcd', 1))

How can I skip the replace command on elements that are not strings?


Solution

  • Your original r appears to be a tuple, not a list, so you may want to retain that as well. You can simply add the condition like this:

    r=(('ab|cd', 1, 'ab|cd', 1), ('ab|cd', 1, 'ab|cd', 1))
    [[x.replace('|', '') if isinstance(x, str) else x for x in l] for l in r]
    

    And to retain the tuple type:

    tuple(tuple(x.replace('|', '') if isinstance(x, str) else x for x in l) for l in r)