Reputation:
I have a list:
list1 = ['field1','field2','field3']
i have used different methods but i is of no help.
list1= ( " ".join( repr(e) for e in list1) )
but it is printing each character in the string as seperate word like
"f","i","e","l","d".
But i want the output like:
list1='field1','field2','field3'
So how can i remove only the brackets from the list without modifying the strings.
Upvotes: 0
Views: 20818
Reputation: 379
I hope this helps. e=[1,2,3] f=re.sub(r'[[]]','',str(e[0]))
Output is : 1
Upvotes: 0
Reputation: 510
most of the previous answers would work, but perhaps the most simplest one is using a for loop:
mylist = ['1','2','3','4']
print('list=',end='')
for myvar in mylist:
print(myvar,end='')
print('')
output:
list=1234
however, this will only work in python 3.4, since you have to use the print function and cannot use a print statement
Upvotes: 0
Reputation: 1190
Tada! str(list1).strip('[').strip(']')
Not sure if it is possible to get python to output:
list1='field1','field2','field3'
That is not valid python syntax... (unless defining a tuple):
>>>list1='field1','field2','field3'
('field1', 'field2', 'field3')
This is the closest you can get:
>>>list1 = ['field1','field2','field3']
# convert list to string
>>>foo = str(list1)
# strip the '[ ]'
>>>print(foo.strip('[').strip(']'))
'field1', 'field2', 'field3'
>>>print("list1=%s" % foo.strip('[').strip(']'))
list1='field1', 'field2', 'field3'
Upvotes: 0
Reputation: 521
It sounds like you want to print your list in a specific format. You can do this using the print()
function in python3 or the print
statement in python2.
First, make a string which represents how you want to output your list:
output = ",".join("'" + item + "'" for item in list1)
There are two steps in this approach. Firstly, we add quotes to the outside of each item in the list, as per your desired output. Secondly, we join the items in the list around a comma.
If you want to have the string 'list1=' at the beginning of the output you can simply prepend it like this:
output = 'list1=' + output
Then, can simply print this string using print output
in python2 or print(output)
in python3.
This should print the following line:
list1='field1','field2','field3'
Upvotes: 1
Reputation: 826
I imagine (the question isn't very clear as noted in the comments) you are looking for:
print ",".join(list1)
Produces:
field1,field2,field3
So how can i remove only the brackets from the list without modifying the strings.
The variable list1
is a list and the []
brackets are included when a list is rendered as a String. You can provide your own string representation as you have here using join
. If you really want to product a string output with the quotes around the strings you could do:
print "'" + "','".join(list1) + "'"
Upvotes: 4