-1

I am trying to express the result of "funct" as a string but nothing I've tried is working.

def funct(y):   
    rad = [2+y]
    return rad
z = 1;
a = funct(z);
print a
print str(a)
b = str(a);
print b
c = repr(a);
print c

Here's my output:

[3]
[3]
[3]
[3]

What am I missing? Thanks!

Edit: I meant that I'm trying to print it as a string without the brackets. Forgot to include that.

5
  • What result do you want? 3? ["3"]? Commented Mar 2, 2014 at 20:35
  • Your first print calls str implicitly, and the second and third prints are doing exactly the same. The fourth print uses repr, which happens to be equivalent to str for a list with integers. If you only want funct to return 2+4, use rad = (2+y) or just rad = 2+y, since [2+y] creates a list with one element. Commented Mar 2, 2014 at 20:39
  • str(a) is a string, what's the problem? Commented Mar 2, 2014 at 20:39
  • just access it with slice notation: ie. a[0] yields "3" Commented Mar 2, 2014 at 20:44
  • possible duplicate of converting a list to a string in python Commented Mar 2, 2014 at 20:55

2 Answers 2

2

You probably don't want rad to be a list.

Try using () instead of []:

rad = (2+y)

Your function would work like so:

def funct(y):   
    rad = (2 + y)
    return rad
z = 1;
a = funct(z);
print a 
#=> "3"
Sign up to request clarification or add additional context in comments.

Comments

0

Based on the title of your question, you don't want to change funct itself and you don't want to convert the output of funct into a string. If you want to change a number into a string you need to change the values inside the list output by funct. The problem is that you're turning the repr of the list itself into a string, but not casting the value in the list:

>>> repr([5])
'[5]'
>>> repr(["5"])
"['5']"

You actually want to cast the value in the list:

>>> repr(list(map(str, [5]))) # say `funct(3)` for example
"['5']"
>>> repr(list(str(i) for i in [5]))
"['5']"

Now, if you really just want to turn the output of funct into a string, you're already doing that. Python's just not printing quotes around the string representation of a list because it's printing it.

>>> repr([5]); print([5])
'[5]'
[5]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.