[Python-de] Alternative zu rpartition

Stefan Schwarzer sschwarzer at sschwarzer.net
Fr Aug 13 13:47:48 UTC 2010


On 2010-08-13 15:29, Stefan Schwarzer wrote:
> def rpartition(s, sep):
>     """Implementation of `rpartition` as a function for Python < 2.5.
> 
>     See http://docs.python.org/library/stdtypes.html#str.rpartition .
> 
>     Warning: Not thoroughly tested.
>     """
>     parts = s.split(sep)
>     # If one of the arguments is a unicode string, returned strings
>     # need to be unicode strings as well. `string_type(...)` may
>     # raise a `UnicodeDecodeError`, which results in the same behavior
>     # as that of `str.rpartition`/`unicode.rpartition`.
>     string_type = type(parts[0])
>     if len(parts) == 1:
>         # Separator not found.
>         empty_string = string_type("")
>         return (empty_string,
>                 empty_string,
>                 string_type(s))
>     else:
>         return (string_type(sep).join(parts[:-1]),
>                 string_type(sep),
>                 string_type(parts[-1]))

Es geht wohl etwas kompakter (aber die ursprüngliche Version ist
meines Erachtens klarer):

def rpartition(s, sep):
    """Implementation of `rpartition` as a function for Python < 2.5.

    See http://docs.python.org/library/stdtypes.html#str.rpartition .

    Warning: Not thoroughly tested.
    """
    parts = s.split(sep)
    # If one of the arguments is a unicode string, returned strings
    # are also unicode strings. `string_type(sep)` may raise a
    # `UnicodeDecodeError`, which is the same behavior as that of
    # `str.rpartition`.
    string_type = type(parts[0])
    if len(parts) == 1:
        # Separator not found.
        returned_sep = string_type("")
    else:
        returned_sep = string_type(sep)
    return (string_type(sep).join(parts[:-1]),
            returned_sep,
            string_type(parts[-1]))

Falls du Unittests schreiben willst, denk daran, dass `assertEqual`
nicht zwischen Byte-Strings und Unicode-Strings unterscheidet.

Viele Grüße
Stefan



Mehr Informationen über die Mailingliste python-de