TypeError: 'str' object is not callable (Python)

后端 未结 16 1139
忘了有多久
忘了有多久 2020-11-22 11:44

Code:

import urllib2 as u
import os as o
inn = \'dword.txt\'
w = open(inn)
z = w.readline()
b = w.readline()
c = w.readline()
x = w.readline         


        
相关标签:
16条回答
  • 2020-11-22 12:08
    str = 'Hello World String'    
    print(str(10)+' Good day!!')
    

    Even I faced issue with the above code as we are shadowing str() function.

    Solution is:

    string1 = 'Hello World String'
    print(str(10)+' Good day!!')
    
    0 讨论(0)
  • 2020-11-22 12:09

    While not in your code, another hard-to-spot error is when the % character is missing in an attempt of string formatting:

    "foo %s bar %s coffee"("blah","asdf")
    

    but it should be:

    "foo %s bar %s coffee"%("blah","asdf")
    

    The missing % would result in the same TypeError: 'str' object is not callable.

    0 讨论(0)
  • 2020-11-22 12:12

    This is the problem:

    global str
    
    str = str(mar)
    

    You are redefining what str() means. str is the built-in Python name of the string type, and you don't want to change it.

    Use a different name for the local variable, and remove the global statement.

    0 讨论(0)
  • 2020-11-22 12:12

    An issue I just had was accidentally calling a string

    "Foo" ("Bar" if bar else "Baz")
    

    You can concatenate string by just putting them next to each other like so

    "Foo" "Bar"
    

    however because of the open brace in the first example it thought I was trying to call "Foo"

    0 讨论(0)
提交回复
热议问题