john
john

Reputation: 192

Printing Values from a list without spaces in python 2.7

Suppose I have a list like

list1 = ['A','B','1','2']

When i print it out I want the output as

AB12

And not

A B 1 2

So far I have tried

(a)print list1,
(b)for i in list1:
    print i,
(c)for i in list1:
    print "%s", %i

But none seem to work. Can anyone suggest an alternate method Thank you.

Upvotes: 1

Views: 3854

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

From your comments on @jftuga answer, I guess that the input you provided is not the one you're testing with. You have mixed contents in your list.

My answer will fix it for you:

lst = ['A','B',1,2]
print("".join([str(x) for x in lst]))

or

print("".join(map(str,lst)))

I'm not just joining the items since not all of them are strings, but I'm converting them to strings first, all in a nice generator comprehension which causes no memory overhead.

Works for lists with only strings in them too of course (there's no overhead to convert to str if already a str, even if I believed otherwise on my first version of that answer: Should I avoid converting to a string if a value is already a string?)

Upvotes: 2

jftuga
jftuga

Reputation: 1963

Try this:

a = "".join(list1)
print(a)

This will give you: AB12

Also, since list is a built-in Python class, do not use it as a variable name.

Upvotes: 0

Related Questions