19

The [f'str'] for string formatting was recently introduced in python 3.6. link. I'm trying to compare the .format() and f'{expr} methods.

 f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '

Below is a list comprehension that converts Fahrenheit to Celsius.

Using the .format() method it prints the results as float to two decimal points and adds the string Celsius:

Fahrenheit = [32, 60, 102]

F_to_C = ['{:.2f} Celsius'.format((x - 32) * (5/9)) for x in Fahrenheit]

print(F_to_C)

# output ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']

I'm trying to replicate the above using the f'{expr} method:

print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]}')  # This prints the float numbers without formatting 

# output: [0.0, 15.555555555555557, 38.88888888888889]
# need instead: ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']

Formatting the float in f'str' can be achieved:

n = 10

print(f'{n:.2f} Celsius') # prints 10.00 Celsius 

Trying to implement that into the list comprehension:

print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]:.2f}') # This will produce a TypeError: unsupported format string passed to list.__format__

Is it possible to achieve the same output as was done above using the .format() method using f'str'?

Thank you.

Darkonaut
  • 20,186
  • 7
  • 54
  • 65
Novice
  • 1,101
  • 4
  • 18
  • 30
  • 2
    Why are you trying to do the list comprehension *inside* the f-string? You didn't do that for the `.format()` version. Looks like you know what how to do it, you just need to not screw it up. – Stefan Pochmann Jan 15 '18 at 01:48
  • If I do it outside the list comp it won't modify each of the elements accordingly. I'm trying to see what type of *expr* can be used in `f'str'`. – Novice Jan 15 '18 at 01:59
  • You *are* doing it outside the list comp. And what does "won't modify each of the elements accordingly" mean? – Stefan Pochmann Jan 15 '18 at 02:01
  • I need it to iteratively modify each element in the list as was done using `.format()` Trying to figure out how to take this output `[0.0, 15.555555555555557, 38.88888888888889]` to `['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']` with `f'str'` using a list comprehension. – Novice Jan 15 '18 at 02:04
  • Again: You've already proven that you already know how to do it. – Stefan Pochmann Jan 15 '18 at 02:09

1 Answers1

32

You need to put the f-string inside the comprehension:

[f'{((x - 32) * (5/9)):.2f} Celsius' for x in Fahrenheit]
# ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius']
Darkonaut
  • 20,186
  • 7
  • 54
  • 65
  • Note: I just ran into a bug (or is it a feature) which means its not allowed to have a space after the formatting operation: `f'{0.3456:.2f}'` << works | `f'{ 0.3456:.2f }'` does not work! – Andy Dec 07 '21 at 13:10