Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "properly" print a list?

Tags:

python

string

So I have a list:

['x', 3, 'b'] 

And I want the output to be:

[x, 3, b] 

How can I do this in python?

If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.

like image 999
Obaid Avatar asked Mar 26 '11 23:03

Obaid


People also ask

How do I print a straight line list?

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 I print a list without a loop?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

How do you print a list without brackets and spaces?

use asterisk '*' operator to print a list without square brackets.


2 Answers

In Python 2:

mylist = ['x', 3, 'b'] print '[%s]' % ', '.join(map(str, mylist)) 

In Python 3 (where print is a builtin function and not a syntax feature anymore):

mylist = ['x', 3, 'b'] print('[%s]' % ', '.join(map(str, mylist))) 

Both return:

[x, 3, b] 

This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".

like image 124
SingleNegationElimination Avatar answered Sep 22 '22 09:09

SingleNegationElimination


This is simple code, so if you are new you should understand it easily enough.

mylist = ["x", 3, "b"] for items in mylist:     print(items) 

It prints all of them without quotes, like you wanted.

like image 32
reemer9997 Avatar answered Sep 22 '22 09:09

reemer9997