string formatting - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: string formatting (/thread-35946.html) |
string formatting - barryjo - Jan-01-2022 When I run this simple program 0.166666666666 is printed. What do i do to make the print 0.17 i.e. what is the formatting command to truncate the string to two digits beyond the dec point?? x = (1/6) s = str(x) print(s) RE: string formatting - bowlofred - Jan-01-2022 You can use either format , or the formatting in f-strings. The description of it from the documentation is found in the Format specification mini-language.>>> x = 1/6 >>> print(x) 0.16666666666666666 >>> print(format(x, ".2f")) 0.17 >>> print(f"{x:.2f}") 0.17 RE: string formatting - barryjo - Jan-01-2022 thanks RE: string formatting - barryjo - Jan-02-2022 oops, another issue. in the following I want to see 12.34. not 1.23+01 i.e. x = 12.345678123456 s = format(x,".2") print(s) RE: string formatting - Larz60+ - Jan-02-2022 print(f"{x: 2.3f}") 12.346 RE: string formatting - snippsat - Jan-02-2022 Use f-string as shown last bye bowlofred.>>> x = 12.345678123456 >>> print(f"The number is {x:.2f} a couple more {x:.4f}") The number is 12.35 a couple more 12.3457 RE: string formatting - barryjo - Jan-02-2022 in the following, is the 3 the digits to the right of the decimal? what does the 2 mean? print(f"{x: 2.3f}") 12.346What if my number was 123456.345 and I want to see 123456.3 RE: string formatting - snippsat - Jan-02-2022 (Jan-02-2022, 01:06 AM)barryjo Wrote: 123456.345 and I want to see 123456.3Then is n:.1f >>> n = 123456.345 >>> print(f"The number with one decimal place {n:.1f}") The number with one decimal place 123456.3 >>> print(f"The number with ten decimal place {n:.10f}") The number with 10 decimal place 123456.3450000000 f'{value:{width}.{precision}}' width specifies the number of characters used in total to display.Some more stuff with f-string >>> n = 123456 >>> print(f"The number in binary {n:02b}") The number in binary 11110001001000000 >>> print(f"The number in hex {n:02X}") The number in hex 1E240 # f-strings can take any Python expressions inside the curly braces >>> grapes = 5.20 >>> apples = 9.70 >>> print(f'The price is {apples + grapes:.2f}$') The price is 14.90$ # Also methods eg .upper() >>> for word in 'f-strings are cool'.split(): ... print(f'{word.upper():~^20}') ... ~~~~~F-STRINGS~~~~~~ ~~~~~~~~ARE~~~~~~~~~ ~~~~~~~~COOL~~~~~~~~ |