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.
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.
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.
List comprehension works with string lists also. The following creates a new list of strings that contains 'a'. Above, the expression if 'a' in s returns True if an element contains a character 'a'.
Python f-string escaping characters To escape a curly bracket, we double the character. A single quote is escaped with a backslash character.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With