Python Forum
why is this variable not printing out properly?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why is this variable not printing out properly?
#11
(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~~~~~~~~
Reply
#12
@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.')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Printing the variable from defined function jws 7 1,160 Sep-03-2023, 03:22 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020