Joining a list of python objects with __str__ method

前端 未结 5 691
孤城傲影
孤城傲影 2021-01-02 09:44

I\'ve already looked at this question on representing strings in Python but my question is slightly different.

Here\'s the code:

>>> class W         


        
相关标签:
5条回答
  • 2021-01-02 09:47

    There are probably no amazing way.

    def strjoin(glue, iterable):
        return glue.join(str(s) for s in iterable)
    
    0 讨论(0)
  • 2021-01-02 09:50

    "...it would be nice to avoid doing that every time..."

    You want to avoid repeating that same code multiple times? Then use a function;:

    def join_as_str(alist):
        return "\n".join(str(item) for item in alist)
    
    0 讨论(0)
  • 2021-01-02 09:58

    You technically aren't joining the list of python objects, just their string representation.

    >>> reduce(lambda x,y: "%s\n%s" % (x,y), weird_list)
    '1302226564.83\n1302226564.83\n1302226564.83'
    >>> 
    

    This works as well but doesn't look any nicer:

    >>> a = ""
    >>> for x in weird_list:
    ...     a+="%s\n" % x
    ... 
    >>> print a
    1302226564.83
    1302226564.83
    1302226564.83
    
    >>>
    
    0 讨论(0)
  • 2021-01-02 10:03

    Would it work for you if you added an __add__ method? E.g.,

    from operator import add
    from random import randint
    
    class WeirdThing(object):
        def __init__(self,me=None):
            self.me = me if me else chr(randint(97,122))
        def __str__(self):
            return "%s" % self.me
        def __repr__(self):
            return ";%s;" % self.me
        def __add__(self,other):
            new_me = add(str(self.me),str(other.me))
            return WeirdThing(new_me)
    
    weird_list = [WeirdThing(), WeirdThing(), WeirdThing()]
    print weird_list
    

    gives,

    [;y;, ;v;, ;u;]
    

    and this,

    strange_thing = reduce(add,weird_list)
    print strange_thing
    

    gives,

    yvu
    
    0 讨论(0)
  • 2021-01-02 10:07

    You have to stringify your objects before you can join them. This is because str.join expects a series of strings, and you must give it a series of strings.

    For the sake of less typing at the cost of readability, you can do "\n".join(map(str, list_of_things).

    0 讨论(0)
提交回复
热议问题