Python 正确的缩进

Python correct indentation

我有一个 python 脚本,其中包含以下部分-

import csv
import mechanize

"""
some code here
"""

with open('data2.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        response2 = browser.open(surl+"0"+row[0])
        str_response = response2.read()
        if "bh{background-color:" in str_response :
            print "Not Found"
        else :

            print "Found " + row[0]
            s_index=str_response.find("fref=search")+13
            e_index=str_response.find("</a><div class=\"bm bn\">")
            print str_response[s_index:e_index]

当我尝试 运行 这个文件时,它显示

行有错误

str_response = response2.read()

它说-

str_response = response2.read() ^ IndentationError: unexpected indent

我是 python 的新手,无法弄清楚这段代码的正确缩进是什么。有人知道我在这里做错了什么吗?

我通过 post 编辑模式复制了您的代码,正如其他人所说,您的缩进混合了制表符和空格。在Python3中,你需要使用其中之一,但不能同时使用。

这是您的原始代码,标签标记为 [TB]

import csv
import mechanize

"""
some code here
"""

with open('data2.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        response2 = browser.open(surl+"0"+row[0])
[TB][TB]str_response = response2.read()
[TB][TB]if "bh{background-color:" in str_response :
[TB][TB][TB]print "Not Found"
[TB][TB]else :

[TB][TB][TB]print "Found " + row[0]
[TB][TB][TB]s_index=str_response.find("fref=search")+13
[TB][TB][TB]e_index=str_response.find("</a><div class=\"bm bn\">")
[TB][TB][TB]print str_response[s_index:e_index]

这里是使用 4 个空格而不是制表符的相同代码:

import csv
import mechanize

"""
some code here
"""

with open('data2.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        response2 = browser.open(surl+"0"+row[0])
        str_response = response2.read()
        if "bh{background-color:" in str_response :
            print "Not Found"
        else :

            print "Found " + row[0]
            s_index=str_response.find("fref=search")+13
            e_index=str_response.find("</a><div class=\"bm bn\">")
            print str_response[s_index:e_index]