Search code examples
pythonstringpositionerase

How to erase letters at any position in a string in python?


For example, my String = 'xx22xx_1x_xxxx-xxxx', x can be any letters. Now I want to delete the first two positions letters xx and seventh position 1, in order to get a NewString = '22xx_x_xxxx-xxxx'. Any function to erase letters at specific positions?


Solution

  • This will do it:

    def erase(string, positions):
        return "".join([y for x,y in enumerate(string) if x not in positions])
    

    demo:

    >>> s='xx22xx_1x_xxxx-xxxx'
    >>> erase(s, (0,1,7))
    '22xx_x_xxxx-xxxx'
    >>>