Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f-string formatting: display number sign?

Basic question about python f-strings, but couldn't find out the answer: how to force sign display of a float or integer number? i.e. what f-string makes 3 displayed as +3?

like image 803
M. Page Avatar asked Dec 17 '21 10:12

M. Page


People also ask

What is %d and %f in Python?

Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.

What is f {} in Python?

The f-string was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast. Example: The f or F in front of strings tells Python to look at the values inside {} and substitute them with the values of the variables if exist.

What two symbols does an F-string work?

The f-strings have the f prefix and use {} brackets to evaluate values. Format specifiers for types, padding, or aligning are specified after the colon character; for instance: f'{price:. 3}' , where price is a variable name.

What is %d in a string?

The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values. Python3.

How to use F-strings in Python to format numbers?

F-strings can also be used to apply number formatting directly to the values. Python can take care of formatting values as percentages using f-strings. In fact, Python will multiple the value by 100 and add decimal points to your precision. To format numbers to a certain precision point, you can use the ‘f’ qualifier.

What is F string in Python?

Python f-string. Python f-string is the newest Python syntax to do string formatting. It is available since Python 3.6. Python f-strings provide a faster, more readable, more concise, and less error prone way of formatting strings in Python. The f-strings have the f prefix and use {} brackets to evaluate values.

What are F-strings and how to use them?

F-strings can also be used to apply number formatting directly to the values. Python can take care of formatting values as percentages using f-strings. In fact, Python will multiple the value by 100 and add decimal points to your precision.

How to call a function in F-string?

We can also call functions in f-strings. The example calls a custom function in the f-string. Python f-string accepts objects as well; the objects must have either __str__ or __repr__ magic functions defined.


Video Answer


4 Answers

From Docs:

  • Format Specification Mini-Language(Emphasis mine):
Option Meaning
'+' indicates that a sign should be used for both positive as well as negative numbers.
'-' indicates that a sign should be used only for negative numbers (this is the default behavior).

Example from docs:

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
>>> '{:+} {:+}'.format(10, -10)
'+10 -10'

Above examples using f-strings:

>>> f'{3.14:+f}; {-3.14:+f}'
'+3.140000; -3.140000'
>>> f'{3.14:-f}; {-3.14:-f}'
'3.140000; -3.140000'
>>> f'{10:+} {-10:+}'
'+10 -10'

One caveat while printing 0 as 0 is neither positive nor negative. In python, +0 = -0 = 0.

>>> f'{0:+} {-0:+}'
'+0 +0'
>>> f'{0.0:+} {-0.0:+}'
'+0.0 -0.0'

0.0 and -0.0 are different objects1.

  • 0 in Computer Science(Emphasis mine):

In some computer hardware signed number representations, zero has two distinct representations, a positive one grouped with the positive numbers and a negative one grouped with the negatives; this kind of dual representation is known as signed zero, with the latter form sometimes called negative zero.


1. Negative 0 in Python. Also check out Signed Zero (-0)

like image 60
Ch3steR Avatar answered Nov 15 '22 12:11

Ch3steR


You can add a sign with an f-string using f"{x:+}", where x is the int/float variable you need to add the sign to. For more information about the syntax, you can refer to the documentation.

like image 44
rchome Avatar answered Nov 15 '22 12:11

rchome


You can use :+ in f-string

number=3
print(f"{number:+}")

Output +3

like image 40
EL-AJI Oussama Avatar answered Nov 15 '22 10:11

EL-AJI Oussama


Like this:

numbers = [+3, -3]

for number in numbers:
    print(f"{['', '+'][number>0]}{number}")

Result:

+3
-3

EDIT: Small time analysis:

import time

numbers = [+3, -3] * 100

t0 = time.perf_counter()
[print(f"{number:+}", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

t0 = time.perf_counter()
[print(f"{number:+.2f}", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

t0 = time.perf_counter()
[print(f"{['', '+'][number>0]}{number}", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

Result:

f"{number:+}"                    => 0.0001280000000000031 s
f"{number:+.2f}"                 => 0.00013570000000000249 s
f"{['', '+'][number>0]}{number}" => 0.0001066000000000053 s

It looks like I have the fastest solution for integers.

like image 27
Vincent Bénet Avatar answered Nov 15 '22 12:11

Vincent Bénet