autopep8

autopep8 would auto-format your python script. not only the code indentation, but also other coding spacing styles. It makes your python script to conform PEP8 Style Guide.

pip install autopep8
autopep8 your_script.py    # dry-run, only print
autopep8 -i your_script.py # replace content

Update:

Many editors have pep8 plugins that automatically reformat your code right after you save the file. py-autopep8 in emacs

yapf

yapf is a new and better python code formatter. which tries to get the best formatting, not just to conform the guidelines. The usage is quite the same as autopep8.

pip install yapf
yapf your_script.py    # dry-run, only print
yapf -i your_script.py # replace content

For more information, like formatting configurations, please read the README.rst on yapf github


Update 2:

Black

Black is much better than yapf. It's smarter and fits most complex formatting cases.

Answer from d2207197 on Stack Overflow
๐ŸŒ
Visual Studio Code
code.visualstudio.com โ€บ docs โ€บ python โ€บ formatting
Formatting Python in VS Code
November 3, 2021 - Open a Python file in VS Code. Right-click on the editor to display the context menu. Select Format Document With....
Discussions

formatting - How do I format text from a file in Python? - Stack Overflow
I have a file that has 50 lines (each line has a name on it) and I would like to take each line and read it, then print it, but in a format that has 5 columns and 10 lines per column. It would like More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is there a format for writing a python script?
PEP8 documentation believe will have everything you are looking for. You can find it on python.org. I just want to point out at how fortunate you are to be learning programming in high-school! I'm almost 29 years old and just started learning python. Before this I had absolutely zero prior computational knowledge. My earlier years consisted of a paint application where you were able to swirl the colors around on the screen. None of the teachers new a thing about computers either. Be proud of where you are at your age already, its an extremely beneficial weapon to have in your arsenal! More on reddit.com
๐ŸŒ r/learnpython
20
23
May 13, 2021
Which code formatter do you use?
Black. We don't care that it may look bad. We don't want to argue about formatting. We know it isn't configurable, that's the point. We don't want to deal with everyone's configuration preferences. More on reddit.com
๐ŸŒ r/Python
144
68
December 21, 2022
Ruff format, new tool to format python files that is 30-120x faster than other tools(e.g black or yapf) - benchmark
What advantage offers that other tools do not? - ignoring speed of course More on reddit.com
๐ŸŒ r/Python
30
70
September 14, 2023
๐ŸŒ
GitHub
github.com โ€บ google โ€บ yapf
GitHub - google/yapf: A formatter for Python files ยท GitHub
Users calling this script directly ... specify formatting style: either a style name (for example "pep8" or "google"), or the name of a file with style settings. The default is pep8 unless a .style.yapf or setup.cfg or pyproject.toml file located ...
Starred by 14K users
Forked by 900 users
Languages ย  Python
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ inputoutput.html
7. Input and Output โ€” Python 3.14.3 documentation
For example: >>> import math >>> print('The value of pi is approximately %5.3f.' % math.pi) The value of pi is approximately 3.142. More information can be found in the printf-style String Formatting section. open() returns a file object, and is most commonly used with two positional arguments and one keyword argument: open(filename, mode, encoding=None)
๐ŸŒ
Python
peps.python.org โ€บ pep-0008
PEP 8 โ€“ Style Guide for Python Code | peps.python.org
Python accepts the control-L (i.e. ^L) form feed character as whitespace; many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_format.asp
Python String format() Method
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary ยท Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module ยท Remove List Duplicates Reverse a String Add Two Numbers ยท Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The format() method formats the specified value(s) and insert them inside the string's placeholder.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ auto-format-your-python-code-with-black
How to Auto-Format Your Python Code with Black
May 12, 2020 - Then Black will format your python file. Now we'll see what Black can help us do. Let's look at this simple example: here are my two python functions in my python file called sample_code.py.
Find elsewhere
๐ŸŒ
Astral
docs.astral.sh โ€บ ruff โ€บ formatter
The Ruff Formatter - Astral Docs
def f(x): """ Something about `f`. And an example: .. code-block:: python ( foo, bar, quux, ) = this_is_a_long_line( lion, hippo, lemur, bear, ) """ pass ยท This feature is currently only available in preview mode. The Ruff formatter can also format Python code blocks in Markdown files.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ fileformats.html
File Formats โ€” Python 3.14.3 documentation
The modules described in this chapter parse various miscellaneous file formats that arenโ€™t markup languages and are not related to e-mail. csv โ€” CSV File Reading and Writing- Module Contents, Diale...
๐ŸŒ
FileFormat.com
docs.fileformat.com โ€บ programming โ€บ py
PY File Format
October 11, 2019 - Python uses new lines to indicate the complete command as opposed to semicolons or parenthesis used in other languages. For scopes, loops, and functions, Python relies on indentation and whitespaces as opposed to curly braces used in other languages. The following is an example of Python syntax.
๐ŸŒ
University of Utah
web.physics.utah.edu โ€บ ~detar โ€บ lessons โ€บ python โ€บ fileio_formatting โ€บ node14.html
Writing to a file with formatting using write()
Next: Writing to a file Up: Writing to a file Previous: Writing to a file ยท If you want to control the formatting, there is another way. The example below illustrates how to write the float x and its square x*x to a file called output.
๐ŸŒ
Google
google.github.io โ€บ styleguide โ€บ pyguide.html
Google Python Style Guide
New unit test files follow PEP 8 compliant lower_with_under method names, for example, test_<method_under_test>_<state>. For consistency(*) with legacy modules that follow CapWords function names, underscores may appear in method names starting with test to separate logical components of the name. One possible pattern is test<MethodUnderTest>_<state>. Python filenames must have a .py extension and must not contain dashes (-).
๐ŸŒ
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
Of course it is also possible to format numbers. ... Similar to strings numbers can also be constrained to a specific width. ... Again similar to truncating strings the precision for floating point numbers limits the number of positions after the decimal point. For floating points the padding value represents the length of the complete output. In the example below we want our output to have at least 6 characters with 2 after the decimal point.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_string_formatting.asp
Python String Formatting
Before Python 3.6 we used the format() method to format strings. The format() method can still be used, but f-strings are faster and the preferred way to format strings. The next examples in this page demonstrates how to format strings with the format() method.
๐ŸŒ
Code Beautify
codebeautify.org โ€บ python-formatter-beautifier
Python Formatter and Beautifier
Python data Try it. HealthInsurance: def __init__(self, name, founded): self.name = name self.founded = founded healthInsurance = HealthInsurance("UnitedHealth", 1977) print(healthInsurance.name) print(healthInsurance.founded) ... Buy us a Coffee JSON Formatter FAQ Privacy Policy Content Policy About Contact History Where am I right now?
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ is there a format for writing a python script?
r/learnpython on Reddit: Is there a format for writing a python script?
May 13, 2021 -

I am currently learning Python in high school. When I installed Spyder to step up the IDE I was previously using (IDLE), there was some pre-written text. Something like this-

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

"""

Created on %(date)s

@author: %(username)s

"""

This made me wonder if there is a properly defined set of 'etiquettes' (if I may) of writing a python script. For starters, I think that you usually write all import statements at the very start and define all the user-built functions after import statements. I want to know if there are any more like these? If you could include a python script of one of your projects (through pastebin or whatever) which may include these etiquettes, that would be awesome.

Also, Would appreciate it if someone could help me out understanding the default Spyder template up there.

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ online_python_formatter.htm
Online Python Formatter | Tutorialspoint
#!/usr/bin/python import re line = "Cats are smarter than dogs"; matchObj = re.match( r'dogs', line, re.M|re.I) if matchObj: print "match --> matchObj.group() : ", matchObj.group() else: print "No match!!" searchObj = re.search( r'dogs', line, re.M|re.I) if searchObj: print "search --> ...
๐ŸŒ
Python Course
python-course.eu โ€บ python-tutorial โ€บ formatted-output.php
22. Formatted Output | Python Tutorial | python-course.eu
Let's have a look at the placeholders in our example. The second one "%8.2f" is a format description for a float number. Like other placeholders, it is introduced with the "%" character. This is followed by the total number of digits the string should contain.