Jon
Jon

Reputation: 9

Add necessary spaces in Python code

Is there any way to automatically format Python code, within Python? So, say for example, I have a string x which equals

if 5 < 7:
print "Yes"
else:
print "No"

and I want to run exec(x), but obviously it'll throw an error because the syntax is incorrect, so is there a way I can change x to

if 5 < 7:
    print "Yes"
else:
    print "No"

and when I run exec(x) it would work? Sorry for my bad English, it's a second language.

Upvotes: 0

Views: 350

Answers (4)

Oleg Butuzov
Oleg Butuzov

Reputation: 5395

In python indents are crucial. You can't allow code fixes to set them instead of a programmer.

Upvotes: 2

0x5453
0x5453

Reputation: 13589

Consider the following input:

if x == 1:
if y == 2:
print 'foo'
else:
print 'bar'

How should your programmatic solution indent the else block?

Like this?

if x == 1:
    if y == 2:
        print 'foo'
    else:
        print 'bar'

Or like this?

if x == 1:
    if y == 2:
        print 'foo'
else:
    print 'bar'

Indentation changes the meaning of the program. It is the job of the programmer to decide what he means, not the computer.

Upvotes: 3

Qwerty
Qwerty

Reputation: 1267

By using autopep8, you can automatically format your code in the pep8 format, check it out.

https://pypi.python.org/pypi/autopep8

Upvotes: 1

Py.Jordan
Py.Jordan

Reputation: 425

For this, it all depends on the IDE you are using. If you use JetBrains Pycharm, you can format the code using a command.

https://www.jetbrains.com/help/pycharm/reformatting-source-code.html

Please let me know what IDE you are using and I may be able to find the command you need to run.

Good luck, Jordan

Edit:

The reason why your code will not run, is because of indentation. As the code is expecting a indent the line for print, it needs the command to complete, once you return to the same level of indentation, it expects that if 3 >7 to be finished with.

Upvotes: 1

Related Questions