Take 3 - multiple arguments to str()

Oren Tirosh oren-py-l at hishome.net
Sun Dec 23 07:21:14 EST 2001


""" str() with multiple arguments.

str([obj1 [, obj2 [...]]]) -> string
unistr([obj1 [, obj2 [...]]]) -> unicode

This enhancement to the str() function/constructor takes an arbitrary 
number of arguments.  The arguments are converted to strings and 
concatenated.  It is backward compatible with the 0 and 1 argument cases.

The multiple argument version of str may be used to defeat the print
statement's automatic spacing and for general formatting of strings
with embedded expressions.

  print str("X=",x," Y=",calc_y(x))

The function unistr() behaves similarly but produces unicode strings.
It differs from the unicode() constructor not only in taking multiple
arguments - like str(), unistr() can convert objects of any type to a
unicode string.  There is no support for encodings in unistr(). Use 
<string>.decode() or the unicode() constructor with two arguments for 
non-default encodings.

Credit for ideas:
 Fredrik Lundh <fredrik at pythonware.com>
 Marcin 'Qrczak' Kowalczyk <qrczak at knm.org.pl>
 yours truly <oren at hishome.net>
"""

import __builtin__


def str(*args):
    """str([obj1 [, obj2 [...]]]) -> string"""

    return ''.join(map(__builtin__.str, args))


def unistr(*args):
    """unistr([obj1 [, obj2 [...]]]) -> unicode"""

    def unistr1(obj):
        if isinstance(obj, unicode):
            return obj
        elif hasattr(obj, '__unistr__'):
            return obj.__unistr__()
        else:
            return unicode(__builtin__.str(obj))

    return ''.join(map(unistr1, args))





More information about the Python-list mailing list