How can I tell if a python variable is a string or a list?

后端 未结 8 1810
孤独总比滥情好
孤独总比滥情好 2020-12-02 19:45

I have a routine that takes a list of strings as a parameter, but I\'d like to support passing in a single string and converting it to a list of one string. For example:

8条回答
  •  盖世英雄少女心
    2020-12-02 20:16

    Varargs was confusing for me, so I tested it out in Python to clear it up for myself.

    First of all the PEP for varargs is here.

    Here is sample program, based on the two answers from Dave and David Berger, followed by the output, just for clarification.

    def func( *files ):
        print files
        for f in files:
            print( f )
    
    if __name__ == '__main__':
        func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3')
        func( 'onestring' )
        func( 'thing1','thing2','thing3' )
        func( ['stuff1','stuff2','stuff3'] )
    

    And the resulting output;

    ('file1', 'file2', 'file3')
    file1
    file2
    file3
    ('onestring',)
    onestring
    ('thing1', 'thing2', 'thing3')
    thing1
    thing2
    thing3
    (['stuff1', 'stuff2', 'stuff3'],)
    ['stuff1', 'stuff2', 'stuff3']
    

    Hope this is helpful to somebody else.

提交回复
热议问题