Python Forum

Full Version: why is this variable not printing out properly?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(Apr-08-2018, 04:21 PM)IAMK Wrote: [ -> ]Could you please explain why that is?
To me, a simple typecast to string seems cleaner.
It's string formatting,try to format a string with typecast +,'" can get very ugly soon.
city = 'Oslo'
temperature = 25
finance = 123.92978665554154545

print(f'City "{city}" temperature {temperature} and fiance stands in marked {finance:.2f}')
Output:
City "Oslo" temperature 25 and fiance stands in marked 123.93
No string formatting.
print('City ' + '"' + city + '"' + ' temperature ' + str(temperature) + ' and fiance stands in marked', finance)
Output:
City "Oslo" temperature 25 and fiance stands in marked 123.92978665554155
f-strings can take any Python expressions inside the curly braces.
Some super power.
>>> name = 'f-string'
>>> print(f"My cool string formatting is called {name.upper():*^20}")
My cool string formatting is called ******F-STRING******
 
>>> cost = 99.75999
>>> finance = 50000
>>> print(f'Toltal cost {cost + finance:.2f}')
Toltal cost 50099.76
 
>>> for word in 'f-strings are cool'.split():
...     print(f'{word.upper():~^20}')
...     
~~~~~F-STRINGS~~~~~~
~~~~~~~~ARE~~~~~~~~~
~~~~~~~~COOL~~~~~~~~
@snippsat, Thanks for the response. The print(f is really nice.
I was under the impression that a typecast would simply be
print('The city's temperature is ' + string(variabletemperature) + ' degrees.')
Pages: 1 2