6

Is there a way in Python to cat a string and a function?

For example

def myFunction():
    a=(str(local_time[0]))
    return a

b="MyFunction"+myFunction

I get an error that I cannot concatenate a 'str' and 'function' object.

2
  • 1
    Did you want to use the return value of myFunction() here? Commented Apr 18, 2013 at 16:17
  • 1
    If you are trying to just use the name, you could use __name__ with myFunction and then concatenate them. (stackoverflow.com/a/255297/758446) Commented Apr 18, 2013 at 16:19

3 Answers 3

15

There are two possibilities:

If you are looking for the return value of myfunction, then:

print 'function: ' + myfunction() 

If you are looking for the name of myfunction then:

print 'function: ' + myfunction.__name__ 
Sign up to request clarification or add additional context in comments.

2 Comments

I want to cll the function like b="MyFunction"+myFunction(), sorry, I missed the () above. I am used to C++. I want to run the function in the statement declaring b, is that possible? I can do it if I run myFunction() outside of declaring b but I want to do it during that declaration, is it possible in python?
Calling the function will return a string. See the code here: ideone.com/UCUMgO.
3

You need to call your function so that it actually returns the value you are looking for:

b="MyFunction"+myFunction()

2 Comments

When I do that I ger the error that I cannot concatenate a 'str' and 'function' object.
@user2295959, it worked for me... Did you notice the parenthesis?
-1

You can use

var= "string" + str(function())

example

a="this is best"
s="number of chars. in a " + str(len(a))
print(s)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.