【问题标题】:PyCharm not fixing indentation when code is pasted粘贴代码时 PyCharm 未修复缩进
【发布时间】:2015-03-02 20:59:31
【问题描述】:

我有一些python代码:

def sameDay(date, dayOfWeek, week, year):    

theDay = datetime.fromtimestamp(
mktime(time.strptime("%s %s %s %s %s" % ("12", "00", dayOfWeek, week, year), "%H %M %w %W %Y")))
return theDay.date() == date.date()


def zeroPadding(string):    

integer = int(string)
if integer < 10:
return "0" + str(integer)
else:
return str(integer)

当我将这些行粘贴到 PyCharm 中时,缩进不固定,我无法编译代码。我曾尝试使用 "Reformat Code" 选项,但这不起作用。我检查了“智能缩进粘贴行”也没有结果。

如何修复缩进,以便在 PyCharm 中编译我的程序?

Here is a snapshot of the issue.

【问题讨论】:

  • “编译”在 Python 中不存在。只有模块或导入文件的准备阶段来生成预先优化的代码,其余的发生在运行时。

标签: python pycharm


【解决方案1】:

编辑不可能这样做。

Python 中的缩进有意义。缩进代码表示语言语法中的一个块,并更改代码的执行方式。一旦缩进丢失,就无法查看代码并辨别其含义。

我们可以像人类一样做出有根据的猜测,但自动化这是不可能的。重新格式化代码自然不会做任何事情,因为缩进不是 Python 中的格式化。我想“智能缩进”只是根据您的项目设置从制表符变为空格或相反。

在您的示例中-假设它全部位于模块的顶层,并且由于return 语句/没有太多嵌套,它几乎是明确的,但是第二个函数可能嵌套在第一个函数中。

例如:

if x < 1:
...
if y < 2:
...
else:
...

可能是:

if x < 1:
    ...
    if y < 2:
        ...
else:
    ...

或:

if x < 1:
    ...
    if y < 2:
        ...
    else:
        ...

Python 中的缩进丢失就像从任何语言的源代码中删除随机字符一样。您丢失了一些代码,需要使用您对代码的理解来重建它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多