, '%', '^', '&', '*...">

Remove characters from a string repeatedly

>>> split=['((((a','b','+b']
>>> [ (w[1:] if w.startswith((' ','!', '@', '#', '$', '%', '^', '&', '*', "(", ")", '-', '_', '+', '=', '~', ':', "'", ';', ',', '.', '?', '|', '\\', '/', '<', '>', '{', '}', '[', ']', '"')) else w) for w in split]
['(((a','b','b']

      

I wanted ['a', 'b', 'b']

this instead.

I want to create a repeat function to repeat a command. I make my split clear all '('

from the start. Suppose my split is longer, I want to clear everything (((

before words. I am not using replace

because it will change '('

between words.

eg. if '('

is in the middle of a type word 'aa(aa'

, I don't want to change that.

+3


source to share


1 answer


There is no need to repeat your expression, you are not using the right tools, that is all. You are looking for a method str.lstrip()

:

[w.lstrip(' !@#$%^&*()-_+=~:\';,.?|\\/<>{}[]"') for w in split]

      

The method treats the string argument as a character set and does exactly what you tried to do in your code; remove the leftmost character multiple times if it is part of this set.

There is a suitable one str.rstrip()

to remove characters from the end, and str.strip()

to remove them from both ends.



Demo:

>>> split=['((((a', 'b', '+b']
>>> [w.lstrip(' !@#$%^&*()-_+=~:\';,.?|\\/<>{}[]"') for w in split]
['a', 'b', 'b']

      

If you really need to repeat the expression, you can simply create a new function for this task:

def strip_left(w):
    while w.startswith((' ','!', '@', '#', '$', '%', '^', '&', '*', "(", ")", '-', '_', '+', '=', '~', ':', "'", ';', ',', '.', '?', '|', '\\', '/', '<', '>', '{', '}', '[', ']', '"')):
        w = w[1:]
    return w

[strip_left(w) for w in split]

      

+8


source







All Articles