簡體   English   中英

VSCode Python 保存時在打印時添加額外的空間

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

我正在使用 VSCode 嘗試 Python ,它讓我對格式化感到頭疼。 我有以下代碼:

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 給我以下錯誤:

無效語法(第 10 行)

發生此錯誤是因為它在 except 打印語句中的 % 之后添加了一個額外的空格,如下所示:

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

有人可以指出我如何解決這個問題的正確方向嗎? 我很確定這是因為格式化程序,但是如何,何時,哪一個?

提前致謝

刪除百分號前的逗號:

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

百分號是格式化運算符。 它需要左邊的字符串和插入右邊的字符串的東西,它不是打印 function 的單獨參數。

此外,最好使用str.format

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

或者如果您使用的是 python 3.6 及更高版本,請使用f-strings

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

你可以在這里閱讀更多關於它的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM