(Python-3): Why is the str() function behaving weirdly?

(Python-3): Why is the str() function behaving weirdly?
0

#1
def stringer(x):
    str(object=x)
    alpha = 'objs['+x+']'
    return alpha

I just ran a sample query to check a part of my code here:

print stringer(3)

and I get a response that str and int cannot be concatenated. I have tried it with this snippet code too and get the same error.:

def stringer(x):
    str(x)
    alpha = 'objs['+x+']'
    return alpha

what is wrong with my code?
thank you :slight_smile:
http://srujanmhase.github.io


#2

First of all, what are you trying to accomplish with the stringer function? If you want to convert x into a string, you need to do something like:

x_str = str(x)

If you have the following:

def stringer(x):
    alpha = 'objs['+str(x)+']'
    return alpha
    
print(stringer(3))  

the function returns a string


#3

Are you only trying to concatenate? Iā€™d suggest the following code:

def stringer(x):
    return "objs[%d]" % (x)

print stringer(3)

Clean and concise - pythonic!