rStorms
rStorms

Reputation: 1115

Assign expression to a variable and use it in another function

I got the following code, that should be used in another function, so I want to pass it using a variable

soup.find("div", {"class" : "article-entry text"}).text.replace('\n', "")

Using

textFormat = "soup.find("div", {"class" : "article-entry text"}).text.replace('\n', "")"

doesn't work obviously. Do I have to escape characters? How?

What would be the best way to execute the content of textFormat. Like so?

text = exec(textFormat)

Thanks!

Upvotes: 0

Views: 53

Answers (3)

Grigory
Grigory

Reputation: 679

You need to escape quotes that your string is surrounded by. Moreover you need to use raw string, to escape other chars. So ...:

textFormat = r'soup.find("div", {"class" : "article-entry text"}).text.replace(\'\n\', "")' 

But if you need to apply function that is have partially fixed elements you should just use partial from functools, not this ad hoc with eval. Using partial you can fix common arguments and pass others that are not common on every call.

Upvotes: 1

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13763

You can wrap it in another function like this:

def textFormat():
    return soup.find("div", {"class" : "article-entry text"}).text.replace('\n', "")

Then use it like this:

text = textFormat()

If you want to pass it to another function:

def func(another_func):
    return another_func()

func(textFormat)

Upvotes: 1

Jefferson Houp
Jefferson Houp

Reputation: 856

Use lambda:

soup_find = lambda x,y: soup.find(x,y).text.replace('\n', '')
soup_find("div", {"class" : "article-entry text"})

Upvotes: 1

Related Questions