StringLiteralNoObjectObserved

One needs to call str to instantiate a str object from a string literal
A string literal represents a str object and can be treated as such
CorrectionHere is what's right.
All these three expressions create a str
object:
'Hello'
str('Hello')
str(str('Hello'))
However, the second expression uses the literal 'Hello'
, which already refers to a str
object, as an argument to the str
function.
str(obj)
behaves differently depending on obj
’s implementation of the __str__()
method. In our case, calling str('Hello')
is equivalent to 'Hello'.__str__()
, which translates to 'Hello'
.
Note that if the __str__()
method is not implemented in obj
, then str(obj)
falls back to returning repr(obj)
.
The following execution steps showcase how the third expression is evaluated:
str(str('Hello'))
str('Hello'.__str__())
str('Hello')
'Hello'.__str__()
'Hello'
SymptomsHow do you know your students might have this misconception?
Novices may write code like this:
name = str('John Doe')
possibly by analogy with:
addr = Address('1235 Military Trail')
They may also never call methods on string literals, like:
'Hello'.upper(),
'Hello'.count('l')
ValueHow can you build on this misconception?
This misconception provides an opportunity to discuss how “everything is an object” in Python, including string literals, but also number literals, boolean literals, etc.