str.strip
is the best approach for this situation, but more_itertools.strip
is also a general solution that strips both leading and trailing elements from an iterable:
Code
import more_itertools as mit
iterables = ["231512-n\n"," 12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']
Details
Notice, here we strip both leading and trailing "0"
s among other elements that satisfy a predicate. This tool is not limited to strings.
See also docs for more examples of
more_itertools.strip
: strip both endsmore_itertools.lstrip
: strip the left endmore_itertools.rstrip
: strip the right endmore_itertools
is a third-party library installable via > pip install more_itertools
.