Python | Check if a variable is a string

Method # 1: Using isinstance (x, str)

This method can be used to check if a variable is specific data type. By specifying the second argument as “str”, we can check if the variable we are passing is a string or not.

# Python3 demo code
# Check if the variable is a string
# using isinstance ()

 
# initialization string

test_string = "GFG"

 
# print the original line

print ( "The original string:" + str (test_string))

  
# using isinstance ()
# Check if the variable is string

res = isinstance (test_string, str )

 
# print result

print ( "Is variable a string? : " + str (res))

Output:

 The original string: GFG Is variable a string ?: True 

Method # 2: Using type()

This problem can also be solved using a type function where we just need to pass a variable and set it to a specific type.

# Python3 demo code
# Check if the variable is a string
# using type ()

  
# initialization string

test_string = "GFG"

  
# print original line

print ( "The original string:" + str (test_string))

 
# using type ()
# Check if the variable is a string

res = type (test_string) = = str

  
# print result

print ( " Is variable a string? : " + str (res))

Output:

 The original string: GFG Is variable a string ?: True