开发者

Storing list variables as a string and storing it as a variable

I am trying to enter list items into a string. I then want to store the string as a varia开发者_如何学Cble 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


How about this:

>>> ''.join([str(x) for x in [1, 2, 3]])
'123'


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'


  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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜