Skip to content

Instantly share code, notes, and snippets.

@nayan108
Last active January 10, 2024 07:47
Show Gist options
  • Save nayan108/533e002240737700d1049753d7697ded to your computer and use it in GitHub Desktop.
Save nayan108/533e002240737700d1049753d7697ded to your computer and use it in GitHub Desktop.
Python String Formatting

Python String Formats

Number formatting

The following table shows a variety of ways to format numbers with Python's rookie str.format(), including examples of floating-point number formatting and integer formatting. You can use print("FORMAT".format(NUMBER)); to run the example, so you can run: print("{:.2f}".format(3.1415926)); to get the output of the first example.

Number Format Output Description
3.1415926 {:.2f} 3.14 Two decimal places
3.1415926 {:+.2f} +3.14 Two decimal places with signs
-1 {:+.2f} -1.00 Two decimal places with symbols
2.71828 {:.0f} 3 Without decimal points
5 {:0>2d} 05 Number with 0 padding(left fills, width is 2)
5 {:X<4d} 5xxx Number with x padding(right fills, width is 4)
Ten {:X<4d} 10xx Number with x padding(right fills, width is 4)
1000000 {:,} 1,000,000 Comma based numbers
0.25 {:.2%} 25.00% Percentage format
1000000000 {:.2e} 1.00e+09 Exponent notation
13 {:10d} 13 Right alignment (default, width 10)
13 {:<10d} 13 Left alignment (width 10)
13 {:^10d} 13 Middle alignment (width 10)

String.format() basics

The following are two examples of basic string replacement. The symbol {} is the placeholder of the replacement variable. If the format is not specified, the variable value is directly inserted as a string.

S1 = "so much depends upon {}".format("a red wheel barrow")

S2 = "glazed with {} water beside the {} chickens".format("rain", "white")

You can also use the position values of variables to change them in the string, which will be more flexible when formatting. If the order is wrong, you can easily correct it without disrupting all the variables.

S1 = " {0} is better than {1} ".format("emacs", "vim")

S2 = " {1} is better than {0} ".format("emacs", "vim")

Older format string symbol "%"

Before Python2.6, the use of format strings was relatively simpler, although the number of parameters it could receive was limited. These methods are still valid in Python 3.3, but there have been implicit warnings that these methods will be completely eliminated, and there is no clear schedule. [ PEP-3101]

Format floating point numbers:

Pi = 3.14159

Print(" pi = %1.2f ", % pi)

Multiple replacement values

S1 = "cats"

S2 = "dogs"

S3 = " %s and %s living together" % (s1, s2)

There are not enough parameters.

Using the old formatting method, I often make mistakes in "TypeError: not enough arguments for formating string" because I miscount the number of replacement variables. It is easy to miss variables when writing the following code. .

Set = (%s, %s, %s, %s, %s, %s, %s, %s) " % (a,b,c,d,e,f,g,h,i)

For new Python format strings, you can use numbered parameters, so that you don't need to count how many parameters there are.

Set = set = " ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}) ".format(a,b,c,d,e,f,g)

More .format() format string methods

The format() function provides quite a lot of additional features and functions. The following are some useful tips for using .format().

Naming parameters

You can use the new format string as a template engine and use named parameters, so that a strict order is not required.

Madlib = " I {verb} the {object} off the {place} ".format(verb="took", object="cheese", place="table ")

I took the cheese off the table

Reuse the same variable multiple times

Using % format strings requires variables to have a strict order, while the .format() method allows arbitrary arrangement of parameters as shown above, and also allows reuse.

Str = "Oh {0}, {0}! Wherefore art thou {0}?".format("Romeo")

Oh Romeo, Romeo! Wherefore art thou Romeo?

Convert values to different base

You can use the following letters to convert numbers into decimal, hex, octal, binary.

Print("{0:d} - {0:x} - {0:o} - {0:b} ".format(21))

21 - 15 - 25 -10101

Use the format as a function

.Format() can be used as a function, which allows ordinary text to be distinguished from the format in the code. For example, you can include all the formats you need to use at the beginning of the program, and then use them later. This is also a good way to deal with internationalization, which requires not only different texts, but also different digital formats.

Define the format

Email_f = "Your email address was {email}".format

Use it in another place.

Print(email_f(email="bob@example.com"))

Thanks to earthboundkid for providing this skill on reddit.

Other skills

Escasing braces

When using str.format(), if you need to use braces, just write it twice:

Print(" The {} set is often represented as { {0} } ".format("empty"))

The empty set is often represented as {0}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment