Friday, January 17, 2025
HomeTechHow to check if type of a variable is string? - python

How to check if type of a variable is string? – python

In Python, you can check if the type of a variable is a string using the built-in isinstance() function. This function checks whether an object is an instance of a specific class or a subclass thereof.

Syntax:

isinstance(variable, str)
  • variable: The variable you want to check.
  • str: The type you are checking for, in this case, the str type (which represents strings in Python).
See also  How to list files in windows using command prompt (cmd)

Example:

# Example variables
var1 = "Hello, World!"
var2 = 123
var3 = 45.6

# Check if the variable is a string
print(isinstance(var1, str))  # Output: True
print(isinstance(var2, str))  # Output: False
print(isinstance(var3, str))  # Output: False

Explanation:

  • isinstance(var1, str) returns True because var1 is a string.
  • isinstance(var2, str) and isinstance(var3, str) return False because var2 is an integer and var3 is a float, not strings.
See also  How to Track a Mobile Number Location in Google Maps

Alternative Using type()

Another method is to use the type() function, but it’s generally recommended to use isinstance() because it handles inheritance and subclasses better.

# Check if variable is of type string using type()
print(type(var1) == str)  # Output: True

However, isinstance() is more flexible and preferred in most cases.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x