Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python default parameter with format()

Tags:

python

I have a Python question regarding default parameter value:


def command(one="Number 1", a = "{one} .. {two}"):
     two = "Number 2"
     a.format(one=one, two=two)
     return a
print command()

Actual Output: {one} .. {two}

Desired Output: Number 1 .. Number 2

Please let me know if you have any suggestions. Thanks

Followed-up questions:

******

import logging
import sys

def command(one="Number 1", a = "{one} .. {two}"):
    two = "Number 2"
    a = a.format(one=one, two=two)           
    logging.error(a)        # Will print
    #logging.debug(a)        # Will not print

command()

Why logging.error will print, but logging.debug won't print? I thought debug level is lower than that of error, and it should print.

like image 483
user1972031 Avatar asked Nov 15 '25 02:11

user1972031


1 Answers

You need to either reassign a to a = a.format(one=one, two=two) or simply return it.

return a.format(one=one, two=two)

a.format does not change the original string a, strings are immutable so all a.format does is create a new string. Any time you modify a string it creates a new object. Unless you are using concatenation then to change the value of a you need to reassign a to the new object.

str.replace is another example where people get caught:

In [4]: a = "foobar"

In [5]: id(a)
Out[5]: 140030900696000
In [6]: id(a.replace("f","")) # new object
Out[6]: 140030901037120
In [7]: a = "foobar"     
In [8]: a.replace("f","")
Out[8]: 'oobar'
In [9]: a  # a still the same
Out[9]: 'foobar'
In [10]: id(a)
Out[10]: 140030900696000
In [11]: a = a.replace("f","") # reassign a 
In [12]: id(a) 
Out[12]: 140030900732000    
In [13]: a 
Out[13]: 'oobar'
like image 113
Padraic Cunningham Avatar answered Nov 17 '25 20:11

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!