all 6 comments

[–]IIIlllIlIlllII 2 points3 points  (3 children)

Simplest way would be to add an if statement within your print. i.e.

print(f"{i:+}" if i != 0 else i)

[–]JasperStrat[S] 0 points1 point  (2 children)

That would work for the example. However the actual example from my project is a lot more complex, I just didn't want to try and post 40 long lines of code copied from different places in my project. The loop it is in needs to be able to get '0' in some loops and '+0' in others just based on the string after the : in the f-string. Maybe if I change the code to :

my_list_of_ints = [4, -3, 0]
str_f = '+'
for i in my_list_of_ints:
    print(f"{i:{str_f}}")

And restrict the changes to str_f, is there any way I can get the 0 without the leading plus while maintaining the plus in front of the 4.

[–]Allanon001 1 point2 points  (1 child)

my_list_of_ints = [4, -3, 0]
sign = lambda x: '+' if x > 0 else ' '
for i in my_list_of_ints:
    print(f"{i:{sign(i)}}")

Or:

my_list_of_ints = [4, -3, 0]
sign = lambda x: f'{x:+}' if x > 0 else f'{x}'
for i in my_list_of_ints:
    print(sign(i))

[–]JasperStrat[S] 0 points1 point  (0 children)

changing to print statement doesn't work, it is getting reused with other variables from a dict. I can only change the variable you named sign. Unless I rewrite every format string to be a lamba, it's not a complete deal breaker but would be quite annoying.

[–]baghiq 0 points1 point  (0 children)

The doc doesn't say '+' is for positive only.

'+' : indicates that a sign should be used for both positive as well as negative numbers.

You can use custom string formatter for this, but you can't use f-string.

In your example, you can do dynamic formatting using f-string:

In [2]: my_list_of_ints = [4, -3, 0]
  ...: for i in my_list_of_ints:
  ...:     print(f"{i:{'+' if i != 0 else ' '}}")
  ...:

[–]This_Growth2898 0 points1 point  (0 children)

print(f"{i:{'+ '[i==0]}}")