Converting string to tuple without splitting characters

后端 未结 9 1170
逝去的感伤
逝去的感伤 2020-12-02 19:49

I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner.

9条回答
  •  渐次进展
    2020-12-02 20:41

    Subclassing tuple where some of these subclass instances may need to be one-string instances throws up something interesting.

    class Sequence( tuple ):
        def __init__( self, *args ):
            # initialisation...
            self.instances = []
    
        def __new__( cls, *args ):
            for arg in args:
                assert isinstance( arg, unicode ), '# arg %s not unicode' % ( arg, )
            if len( args ) == 1:
                seq = super( Sequence, cls ).__new__( cls, ( args[ 0 ], ) )
            else:
                seq = super( Sequence, cls ).__new__( cls, args )
            print( '# END new Sequence len %d' % ( len( seq ), ))
            return seq
    

    NB as I learnt from this thread, you have to put the comma after args[ 0 ].

    The print line shows that a single string does not get split up.

    NB the comma in the constructor of the subclass now becomes optional :

    Sequence( u'silly' )
    

    or

    Sequence( u'silly', )
    

提交回复
热议问题