-1

New to python (and coding in general) and was hoping for some help understanding this.

Here's some sample code from Ipify:

from requests import get

ip = get('https://api.ipify.org').text
print('My public IP address is: {}'.format(ip))

I don't really understand how the braces are working in second line, but I've tried writing it a few other ways that I understand instead:

ip = get('https://api.ipify.org').text
print(f"my public IP is {ip}")

and

ip = get('https://api.ipify.org').text
print("my public IP is", ip)

My question is how is the code they provided in the first example better and what are the braces doing in their code?

Thanks in advance for any help.

Capn Jack
  • 1,201
  • 11
  • 28
  • 1
    Did you read the `str.format` docs? What do you mean *"better"*? – jonrsharpe Nov 14 '18 at 16:56
  • [str.format](https://docs.python.org/2/library/stdtypes.html#str.format) can be found here. – Torxed Nov 14 '18 at 16:56
  • @jonrsharpe By "better" I think OP just means its more widespread, most common use. I recall seeing somewhere it was preferred for python 3 rather than the old % method in python 2. – Capn Jack Nov 14 '18 at 16:57
  • A reason for doing the first way is being written before Python 3.6 –  Nov 14 '18 at 16:58
  • 2
    Possible duplicate of [String Formatting in Python 3](https://stackoverflow.com/questions/13945749/string-formatting-in-python-3) – Joel Nov 14 '18 at 16:58
  • @Joel completely disagree, OP is asking why the first example is preferred to his other two. OP seems to be aware of the concept of string formatting... – Capn Jack Nov 14 '18 at 17:00
  • @CapnJack I see now how the braces are working after reviewing str.format, but my question is indeed what the advantages to doing this vs the 2 other ways I added (which are shorter). – OptimizedCompute Nov 14 '18 at 17:17

1 Answers1

0

Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces {}

Example:

str = "This code is written in {}"
print(str.format("Python")) 

Output:

This code is written in Python

Why is .format{} better than old Python 2 %?

.format{} accepts tuple while % throws a TypeError

Agile_Eagle
  • 1,710
  • 3
  • 13
  • 32