Jurudocs
Jurudocs

Reputation: 9165

Python Basics: How to convert a list containing an int into a plain int?

Why is this not giving me just "3" but still "[3]"?

a = [3]
print "".join(str(a))

Upvotes: 1

Views: 192

Answers (6)

Ray Thompson
Ray Thompson

Reputation: 1

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)

Upvotes: 0

thedjpetersen
thedjpetersen

Reputation: 29224

This would produce the expected behavior:

"".join([str(x) for x in a])

Upvotes: 1

Alex Reynolds
Alex Reynolds

Reputation: 96937

Perhaps just dereference by index:

print a[0]

Or:

for item in a:
    print item

Upvotes: 3

Useless
Useless

Reputation: 67723

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.

Upvotes: 2

aweis
aweis

Reputation: 5596

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, e.g.:

a = [3, 2]
print "".join([str(v) for v in a]) ## This gives a string and not integer
>>> "32"

Upvotes: 8

David Nehme
David Nehme

Reputation: 21572

You are taking str() on an array. str convers [3] to "[3]". You are probably looking for

"".join(str(i) for i in a)

Upvotes: 4

Related Questions