How to find out if a Python object is a string?

前端 未结 14 1950
天涯浪人
天涯浪人 2020-11-30 17:47

How can I check if a Python object is a string (either regular or Unicode)?

相关标签:
14条回答
  • 2020-11-30 18:41
    isinstance(your_object, basestring)
    

    will be True if your object is indeed a string-type. 'str' is reserved word.

    my apologies, the correct answer is using 'basestring' instead of 'str' in order of it to include unicode strings as well - as been noted above by one of the other responders.

    0 讨论(0)
  • 2020-11-30 18:41

    This evening I ran into a situation in which I thought I was going to have to check against the str type, but it turned out I did not.

    My approach to solving the problem will probably work in many situations, so I offer it below in case others reading this question are interested (Python 3 only).

    # NOTE: fields is an object that COULD be any number of things, including:
    # - a single string-like object
    # - a string-like object that needs to be converted to a sequence of 
    # string-like objects at some separator, sep
    # - a sequence of string-like objects
    def getfields(*fields, sep=' ', validator=lambda f: True):
        '''Take a field sequence definition and yield from a validated
         field sequence. Accepts a string, a string with separators, 
         or a sequence of strings'''
        if fields:
            try:
                # single unpack in the case of a single argument
                fieldseq, = fields
                try:
                    # convert to string sequence if string
                    fieldseq = fieldseq.split(sep)
                except AttributeError:
                    # not a string; assume other iterable
                    pass
            except ValueError:
                # not a single argument and not a string
                fieldseq = fields
            invalid_fields = [field for field in fieldseq if not validator(field)]
            if invalid_fields:
                raise ValueError('One or more field names is invalid:\n'
                                 '{!r}'.format(invalid_fields))
        else:
            raise ValueError('No fields were provided')
        try:
            yield from fieldseq
        except TypeError as e:
            raise ValueError('Single field argument must be a string'
                             'or an interable') from e
    

    Some tests:

    from . import getfields
    
    def test_getfields_novalidation():
        result = ['a', 'b']
        assert list(getfields('a b')) == result
        assert list(getfields('a,b', sep=',')) == result
        assert list(getfields('a', 'b')) == result
        assert list(getfields(['a', 'b'])) == result
    
    0 讨论(0)
提交回复
热议问题