tags:

views:

95

answers:

4

Hello,

I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is:

def b(): 

    ID = [0, 1, 2]
    ID2 = 'ID={0}.{1}.{2}'.format(*ID) 
    return ID2 

if __name__ == '__main__': ID2 = b() 


def c(ID2): 
    print ID2 

if __name__ == '__main__': myObject = c(ID2) 

The output I get is:

[0, 1, 2] 

Any help would be appreciated. Thanks

I was returning the list as well as ID2. This was causing the problem. Sorry about this.

The code is now working. Thanks

+3  A: 

How about this:

>>> ''.join([str(x) for x in [1, 2, 3]])
'123'
aatifh
and what exactly does this *solution* solve?
SilentGhost
I am really not sure what exactly he wants. I am hoping he wants the result some thing like this "ID=0,ID=1,ID=2"
aatifh
the point is that OP doesn't have problem with string formatting. His problem is that he was returning from `b` before he even performed the formatting, and not this code wasn't posted.
SilentGhost
+1  A: 
def b():
    ID = [0, 1, 2]
    ID2 = ('ID=%d.%d.%d' % tuple(ID))
    return ID2

if __name__ == '__main__': ID2 = b()

def c(ID2):
    print ID2

if __name__ == '__main__': myObject = c(ID2)

works for me, don't have python3 handy so cannot try with the .format()-syntax.

However myObject = c(ID2) does not make sense, function c() does not return anything

Kimvais
How about when the length of list is more than 100. Will you write %d hundred times?
aatifh
`.format`-style formatting is available in python2.6
SilentGhost
If the list is longer than 3, I think I'll do a `"ID=%s" % ".".join( ["%d" % x for x in list])`
Kimvais
+2  A: 

If you want to change [0,1,2] to "0.1.2" (like version string in your previous questions), you could do like this.

>>> '.'.join(map(str,[0, 1, 2]))
'0.1.2'
S.Mark
+2  A: 
  1. You should probably not have global variable names that match your function parameter names. It's legal but very, very confusing. And a debugging nightmare.

  2. You should probably not use ALL UPPERCASE VARIABLE NAMES. It's odd-looking and makes your code hard to read for experienced Python programmers.

  3. You should probably not have multiple if __name__ == "__main__" sections. It's very, very confusing and a debugging nightmare.

I suspect that these "cosmetic" issues are making it hard to figure out what's really wrong with your program.

def b(): 
    id = [0, 1, 2]
    aString = 'ID={0}.{1}.{2}'.format(*id) 
    return aString 

def c(id2): 
    print id2 

if __name__ == '__main__': 
    someString = b() 
    myObject = c(someString) 

You might find this a little easier to debug.

My output.

ID=0.1.2

BTW. Your function c always returns None. So the myObject = c(someString) doesn't make a lot of sense.

S.Lott