Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a python function within quotation marks

I'm writing a function that generates some part of a string, and is going to be called within another string, so that it completes the sentence.

The restriction, however, is that this complete string must be set in quotation marks. It looks something like:

date = 'The date is get_date()'

where get_date() is a function that returns the date in a string (though is a little more complicated than that). The problem is that python wont let me call a function within quotation marks.

Any ideas?

Thanks

EDIT: I'll be more specific about what I'm trying to do, since I don't think it's that complicated, and you seem like a helpful bunch.

I've got a configuration file (conf.py) that is defining a bunch of variables. One of them that I'd like to manipulate (using a python script) is copyright year:

one_of_the_options = [('example1', 'Copyright 2008-CURRENTYEAR Company Name Ltd.')]

CURRENTYEAR is what I'd like to control via the output of a python script, where my function just returns the year as a string.

like image 983
user1488804 Avatar asked Feb 03 '26 18:02

user1488804


1 Answers

Try this instead:

date = 'The date is {}'.format(get_date())

The above uses a formatted string, much simpler (and safer) than evaluating code in a string - and the actual function to be evaluated could be passed as a parameter, for increased flexibility. For instance, for the example after the edit:

def get_current_year():
    return '2013' # just an example, not the real function

s = 'Copyright 2008-{} Company Name Ltd.'
s.format(get_current_year())
=> 'Copyright 2008-2013 Company Name Ltd.'

Formatted strings allow you to substitute the {} placeholder within a string with any value you want, in particular, it can be a function call. Read more about format strings in the documentation.

like image 119
Óscar López Avatar answered Feb 06 '26 10:02

Óscar López



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!