Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print out a string and list in one line-python

a=[1,2,3]
print "the list is :%"%(a)

I want to print out one line like this: the list is:[1,2,3] I can not make it within one line and I have to do in this way:

print " the list is :%"
print a

I am wondering whether I can print out something that combine with string formatting and a list in ONE line.

like image 769
user12551 Avatar asked Sep 08 '14 21:09

user12551


People also ask

Can you print a string with a list in Python?

Convert a list to a string for display : If it is a list of strings we can simply join them using join() function, but if the list contains integers then convert it into string and then use join() function to join them to a string and print the string.

How do you print a list of elements on the same line in Python?

When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.

How do you print multiple lines on one line in Python?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3.


4 Answers

I suggest using the string format method, as it is recommended over the old % syntax.

print("the list is: {}".format(a))
like image 55
Roger Fan Avatar answered Oct 04 '22 15:10

Roger Fan


The simplest way is what CodeHard_or_HardCode said in the comments. For Python 3 it would be:

a=[1,2,3]
print('This is a list', a)

This is a list [1, 2, 3]
like image 32
moto Avatar answered Oct 04 '22 16:10

moto


Try this:

a = [1,2,3]
print("the list is: %s" % a)
like image 44
user590028 Avatar answered Oct 04 '22 16:10

user590028


At least in Python 2.7.4., this will work:

print " the list is " + str(a)
like image 34
Newb Avatar answered Oct 04 '22 15:10

Newb