1

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.

john
  • 194
  • 1
  • 2
  • 11

2 Answers2

2

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?)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

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.

jftuga
  • 1,913
  • 5
  • 26
  • 49