简体   繁体   中英

why does my 'join' function run wrong

b=','.join([1,2,3,4,5])
print b

I want it to print the string: '1,2,3,4,5'

In your answers, please try to use code examples rather than text, because my English is not very good. Thank you.

b = ','.join(map(str, [1,2,3,4,5]))
# => '1,2,3,4,5'

Python doesn't automatically turn the ints into strings--you have to convert them to strings first, then join them.

anystring.join takes an iterable of STRINGS , not one of integers, which is what you're passing to it!

So, use ','.join(str(x) for x in range(1, 6)) or the like.

The join function expects strings not integers, if you did b=','.join(["1","2","3","4","5"]) instead it works.

Here's the consoles output:

>>> b=','.join(["1","2","3","4","5"])
>>> print b
1,2,3,4,5
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM