Python Forum
python format conversion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: python format conversion (/thread-11703.html)



python format conversion - bluefrog - Jul-22-2018

Hi

I'm just wondering why I cannot print the following:
#!/usr/bin/python3
some_integer = 10
some_string = "Hello World"
print("{some_integer!r} {some_string!r} ".format(some_integer, some_string))
But the following works:
#!/usr/bin/python3
some_integer = 10
some_string = "Hello World"
print("{0!r} {1!r} ".format(some_integer, some_string))



RE: python format conversion - buran - Jul-22-2018

in the first snippet you try to use f-string, introduced in 3.6. print(f"{some_integer!r} {some_string!r}")
note the f in front of the string

also note that in your example you don't actually need the !r part
even before 3.6 you can do
items = {'foo':'some string', 'bar':'another_string'}
print('{foo} {bar}'.format(** items))
EDIT: fix the leftover from .format() in the f-string example


RE: python format conversion - snippsat - Jul-22-2018

To fix first script with format() alone.
some_integer = 10
some_string = "Hello World"
print("{some_integer!r} {some_string!r} ".format(some_integer=some_integer, some_string=some_string))
Output:
10 'Hello World'
As mention f-string,the look and readability is a better.
some_integer = 10
some_string = "Hello World"
print(f"{some_integer!r} {some_string!r}")
Output:
10 'Hello World'