NameError: name ‘string’ is not defined
This is the common Python Error when you use the word string instead of the keyword str while type conversion or such in your program.
In this tutorial, we shall learn how to recreate this NameError and ways to handle this error.
Recreate NameError
Let us recreate this error.
Output
Traceback (most recent call last):
File "example1.py", line 2, in <module>
s = string(n)
NameError: name 'string' is not defined
What we tried here is to convert a number to string.
But we all know that str(number) converts number to string but not string(number). This is kind of a typo error from the programmer point of view.
Solution to NameError
You have to use the correct Python keywords.
For example, let us correct the above Python program, by replacing the word –string with the correct keyword str.
Summary
In this tutorial of Python Examples, we learned how to solve NameError in our Python programs.
Next Topic ⫸ Python String capitalize()
⫷ Previous Topic Python - Print new line after variable