At 12:04 PM 4/14/2008, Kent Johnson wrote:
Malcolm Greene wrote:
> What is the Pythonic way to remove specific chars from a string? The
> .translate( table[, deletechars]) method seems the most 'politically
> correct' and also the most complicated.

Most 'correct' and also by far the fastest. This recipe makes it a bit
easier to use:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303342

Just a couple of days ago I needed a function to determine the number of significant digits in a real number. It also involves the removal of specific chars from a string, but not all at once. (It ignores the implicit assumption that the digits at the end of the remaining string are actually significant.) This is what I came up with. It works, but could it be improved?

def sigDigits(n):
    """
    Strips any real decimal (as string) to just its significant digits,
    then returns its length, the number of significant digits.
    Examples: "-345" -> "345" -> 3;
    "3.000" -> "3000" -> 4
    "0.0001234" -> "1234" -> 4;
    "10.0001234" -> "100001234" -> 9
    "7.2345e+543" -> "72345" -> 5
    """
    s = str(n).lstrip("-+0")
    s = s.lstrip(".")
    s = s.lstrip("0")
    s = s.lstrip(".")
    s = s.replace(".", "")
    if "e" in s:
        s = s.rstrip("+-0123456789")
        s = s.rstrip("e")
    return len(s)

Thanks,

Dick Moores

           ================================
UliPad <<The Python Editor>>: http://code.google.com/p/ulipad/

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to