Why is this not giving me just "3" but still "[3]"?
a = [3]
print "".join(str(a))
because you call the to string function on the entire list
try:
a = [3]
print "".join([str(v) for v in a])
After reading the headline of the question are you just trying to get a single integer from a list, or do you want to convert a list of integer into a "larger" integer, eg:
a = [3, 2]
print "".join([str(v) for v in a]) ## This gives a string and not integer
>>> "32"
You are taking str() on an array. str convers [3] to "[3]". You are probably looking for
"".join(str(i) for i in a)
Perhaps just dereference by index:
print a[0]
Or:
for item in a:
print item
Because str(a)
gives you the string representation of a list, ie, "[3]".
Try
"".join([str(elem) for elem in a])
to convert the list of ints to a list of strings before joining.
这将产生预期的行为:
"".join([str(x) for x in a])
Pass in a generator expression to join rather then a list comprehension:
"".join(str(x) for x in a)
If your list only contains numbers you might use repr() instead since thats what str() is going to do anyway:
"".join(repr(x) for x in a)
If your using python 2.X you can use backticks as a shortcut for repr(). But this isn't available in 3.X:
"".join(`x` for x in a)
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.