# How to check if a variable is a string in Python

> Learn how to check if a variable is a string in Python using the type() function or isinstance(), comparing the value against the built-in str class.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-03-01 | Updated: 2026-08-07 | Topics: [Python](https://flaviocopes.com/tags/python/) | Canonical: https://flaviocopes.com/python-check-string/

You can check if a variable is a string in Python in two ways: comparing its `type()` to the `str` class, or calling `isinstance()`. Both work, and I'll show you when to prefer one over the other.

The first way uses the `type()` function, passing the variable as an argument, and then comparing the result to the `str` class:

```python
name = "Roger"
type(name) == str  # True
```

The second way uses `isinstance()`, passing 2 arguments: the variable, and the `str` class:

```python
name = "Roger"
isinstance(name, str)  # True
```

Any non-string value fails both checks, as you'd expect:

```python
age = 8
isinstance(age, str)  # False
```

## Which one should you use?

My advice is to use `isinstance()`. The difference shows up with subclasses.

`type()` returns the exact class of the value. If someone defines a class that inherits from `str`, the `type()` comparison fails, while `isinstance()` still recognizes it as a string:

```python
class UserId(str):
    pass

uid = UserId("abc123")

type(uid) == str  # False
isinstance(uid, str)  # True
```

In most programs a `UserId` should be usable anywhere a string is, so `isinstance()` gives you the answer you actually want. This is also what PEP 8 recommends for type comparisons.

## The bytes pitfall

Here's a case that trips people up. Data read from a file opened in binary mode, or received over a network socket, is `bytes`, not `str`. It prints almost like a string, but it fails the check:

```python
data = b"Roger"
isinstance(data, str)  # False
```

If your check returns `False` when you swear you have a string, print `type(data)` and look at it. If you see `bytes`, decode it first:

```python
text = data.decode("utf-8")
isinstance(text, str)  # True
```

## Checking before using string methods

A common reason for this check is guarding code that calls string methods, when a value might be a string or something else, like `None`:

```python
def shout(value):
    if isinstance(value, str):
        return value.upper()
    return ""

shout("hello")  # 'HELLO'
shout(None)     # ''
```

Without the guard, `None.upper()` raises `AttributeError`. The `isinstance()` check keeps the function safe with any input.
