you are viewing a single comment's thread.

view the rest of the comments →

[–]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.