简体   繁体   English

VSCode Python 保存时在打印时添加额外的空间

[英]VSCode Python adding extra space after % on print when save

I am trying Python with VSCode and it is giving me a headache with formatting.我正在使用 VSCode 尝试 Python ,它让我对格式化感到头疼。 I have te following code:我有以下代码:

import os
filePath = "get-file-size.py"

try:
    size = os.path.getsize(filePath)

except OSError:
    print("Path '%s' does not exist or is not accesible", %filePath)
    sys.exit()

print("File size (in bytes): ", size)

VSCode gives me the following error: VSCode 给我以下错误:

invalid syntax (, line 10)无效语法(第 10 行)

This error happens because it adds an extra space after % in the except print statement as below:发生此错误是因为它在 except 打印语句中的 % 之后添加了一个额外的空格,如下所示:

print("Path '%s' does not exist or is not accesible", % filePath)

Can someone point me in the right direction on how to solve this?有人可以指出我如何解决这个问题的正确方向吗? I am pretty sure it is because a formatter, but how, when, which one?我很确定这是因为格式化程序,但是如何,何时,哪一个?

Thanks in advance提前致谢

Delete the comma before the percent sign:删除百分号前的逗号:

print("Path '%s' does not exist or is not accesible" % filePath)

The percent sign is the formatting operator.百分号是格式化运算符。 It takes a string on the left and stuff to insert to the string on the right, it's not a separate argument of the print function.它需要左边的字符串和插入右边的字符串的东西,它不是打印 function 的单独参数。

Also, it's better to use str.format :此外,最好使用str.format

print("Path '{}' does not exist or is not accesible".format(filePath))

or if you're using python 3.6 and above, use f-strings :或者如果您使用的是 python 3.6 及更高版本,请使用f-strings

print(f"Path '{filePath}' does not exist or is not accesible")

You can read more about it here .你可以在这里阅读更多关于它的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM