Python Forum
python format conversion
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python format conversion
#1
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))
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python for syntax conversion kingsman 23 9,309 Apr-27-2020, 03:24 PM
Last Post: kingsman

Forum Jump:

User Panel Messages

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