简体   繁体   中英

printing multiple lists in python

Hey I wrote a python code (python 2.7.3) with multiple lists, but when I try to print them they always come with a space. I want to print the list in continuous manner but I'm unable to do so. I have one list which have integer values and other with character.

Eg: list1 (integer list has 123) and list2(character list has ABC).

Desired Output: ABC123 What I'm getting: ABC 123

What I did:

print "".join(list2),int("".join(str(x) for x in list1))

Any suggestion what I'm doing wrong?

l = ["A","B","C"]
l2 = [1,2,3]
print "".join(l+map(str,l2))
ABC123

map casts all ints to str , it is the same as doing [str(x) for x in l2] .

The space comes from the print statement. It automatically inserts a space between items separated with comma. I suppose you don't need to covert the concatenated string into an integer, then you concatenate strings from join and print them as one.

print "".join(list2)+"".join(str(x) for x in list1)

Alternatively you can switch to python3's print function, and use its sep variable.

from __future__ import print_function
letters=['A','B','C']
nums=[1,2,3]
print("".join(letters),int("".join(str(x) for x in nums)), sep="")

The , is what's adding the space since you are printing two things, a string 'ABC' and an integer 123. Try using + , which directly adds two strings together so you can print the string 'ABC123'

>>> list1=[1,2,3]
>>> list2=['A','B','C']
>>> print "".join(list2),int("".join(str(x) for x in list1))
ABC 123
>>> print "".join(list2)+"".join(str(x) for x in list1)
ABC123

Try concatenating the two lists you want while printing. Use "+" instead of ",". Here 'int' will give error as you can concatenate only strings. So try,

 print "".join(list2)"".join(str(x) for x in list1)

print adds a single space automatically between commas.

You can use the new print function:

from __future__ import print_function 
print("".join(list2),int("".join(str(x) for x in list1)), sep="")

See docs .

Note: This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module

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