Jorge
Jorge

Reputation: 79

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. 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:

invalid syntax (, line 10)

This error happens because it adds an extra space after % in the except print statement as below:

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

Upvotes: 0

Views: 447

Answers (1)

assembly_wizard
assembly_wizard

Reputation: 2064

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.

Also, it's better to use 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:

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

You can read more about it here.

Upvotes: 2

Related Questions