0

Can someone explain to me what is going on with the .format() method that it only works off a string declaration and not on a variable containing a string?

Below are the example of the working and failing code followed by the output of each

# This works fine
s = "{0} \n" \
    "{1} \n" \
    "{2}\n" \
    .format("Hello", "world", "from a multiline string")
print(s)

# This does not
f = "{0} \n" \
    "{1} \n" \
    "{2}\n"

f.format("Hello", "world", "from a multiline string")
print(f)

respective output

Hello 
world 
from a multiline string

{0} 
{1} 
{2}

I have tried this with no numbers in braces({}) as well as by assigning names ({aname}) and passing keyword arguments. I'd like to understand the difference between the first and second examples in how the format method processes them, and if there is a way to format a variable containing a string separate from the actual declaration.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dave
  • 592
  • 3
  • 15

2 Answers2

6

It is working, but you will need to reassign it back since it is not in-place (= it creates a new string object, just like any other str method).

f = "{0} \n" \
    "{1} \n" \
    "{2}\n"
f = f.format("Hello", "world", "from a multiline string")
print(f)
#  Hello 
#  world 
#  from a multiline string
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Oh my word... This is what happens when you code at 4:30 AM and you're used to sleeping. I'll accept it as soon as the time lapses. Thanks DeepSpace – Dave May 14 '18 at 09:22
5

because .format function returns the formatted string.

It doesn't format the string on which it's called, but it will return you a new string object having the formatted result.

harshil9968
  • 3,254
  • 1
  • 16
  • 26