In Python 3.x, the correct way to check if s is a string is
isinstance(s, str)
The bytes class isn't considered a string type in Python 3.
In Python 2.x, the correct check was
isinstance(s, basestring)
basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of either str or unicode.
In Python 3.x, the correct way to check if s is a string is
isinstance(s, str)
The bytes class isn't considered a string type in Python 3.
In Python 2.x, the correct check was
isinstance(s, basestring)
basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of either str or unicode.
I know this is an old topic, but being the first one shown on google and given that I don't find any of the answers satisfactory, I'll leave this here for future reference:
six is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like this:
import six
if isinstance(value, six.string_types):
pass # It's a string !!
Inspecting the code, this is what you find:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
How can you check if a string contains any one character from a set of characters?
[Beginner question] How do I check if an input is a string, float, or integer in 2.7 without changing it?
Videos
Is there some easy, built-in way to check if a given string contains at least one single digit, 0-9? Everything I'm searching talks about the in operator or the find method, but those seem to require that you already know which digit you are looking for.
I'm leaning toward using an RE, but I wanted to know if there was a simpler way first.
Examples that would evaluate to true would be:
'44 a b' 'aa ba 5' '45 187'
and false would be any string without at least one digit.
I figure I can just try to match it with \d+, but I don't want to rely on REs too much, even though I find them fun!
Thanks!
Python 2
Use isinstance(obj, basestring) for an object-to-test obj.
Docs.
Python 3
In Python 3.x basestring is not available anymore, as str is the sole string type (with the semantics of Python 2.x's unicode).
So the check in Python 3.x is just:
isinstance(obj_to_test, str)
This follows the fix of the official 2to3 conversion tool: converting basestring to str.
Hello! I recently decided to pick up python 2.7 for a project in my computer science class, but my area has been quarantined by covid-19 and I'm unable to ask my teacher for any help. I'm making a basic unit-conversion calculator, and I'd like to be able to tell what a user is inputting, without changing it. For example, if they put in a string, it would display a message such as "Sorry, only numbers are allowed" and allows the user to try again. I'm using the raw_input() function to get the input, but idk how to discern strings, floats, and integers.