Skip to content Skip to sidebar Skip to footer

Make List To String Python

I want to make list data to string. My list data like this : [['data1'],['data2'],['data3']] I want to convert to string like this : '[data1] [data2] [data3]' I try to use join l

Solution 1:

Depending on how closely you want the output to conform to your sample, you have a few options, show here in ascending order of complexity:

>>>data=[['data1'],['data2'],['data3']]>>>str(data)
"[['data1'], ['data2'], ['data3']]"
>>>' '.join(map(str, data))
"['data1'] ['data2'] ['data3']"
>>>' '.join(map(str, data)).replace("'", '')
'[data1] [data2] [data3]'

Keep in mind that, if your given sample of data doesn't match your actual data, these methods may or may not produce the desired results.

Solution 2:

Have you tried?

data=[['data1'],['data2'],['data3']]
t =  map(lambda x : str(x), data)
print(" ".join(t))

Live demo - https://repl.it/BOaS

Solution 3:

In Python 3.x , the elements of the iterable for str.join() has to be a string .

The error you are getting - TypeError: sequence item 0: expected string, list found - is because the elements of the list you pass to str.join() is list (as data is a list of lists).

If you only have a single element per sublist, you can simply do -

" ".join(['[{}]'.format(x[0]) for x in data])

Demo -

>>>data=[['data1'],['data2'],['data3']]>>>" ".join(['[{}]'.format(x[0]) for x in data])
'[data1] [data2] [data3]'

If the sublists can have multiple elements and in your output you want those multiple elements separated by a , . You can use a list comprehension inside str.join() to create a list of strings as you want. Example -

" ".join(['[{}]'.format(','.join(x)) for x in data])

For some other delimiter other than ',' , use that in - '<delimiter>'.join(x) .

Demo -

>>>data=[['data1'],['data2'],['data3']]>>>" ".join(['[{}]'.format(','.join(x)) for x in data])
'[data1] [data2] [data3]'

For multiple elements in sublist -

>>>data=[['data1','data1.1'],['data2'],['data3','data3.1']]>>>" ".join(['[{}]'.format(','.join(x)) for x in data])
'[data1,data1.1] [data2] [data3,data3.1]'

Solution 4:

>>> import re
>>> l = [['data1'], ['data2'], ['data3']]
>>> s = "">>> for i in l:
        s+= re.sub(r"\'", "", str(i))
>>> s
'[data1][data2][data3]'

Solution 5:

How about this?

data = [['data1'], ['data2'], ['data3']]
result = " ".join('[' + a[0] + ']'for a in data)
print(result)

Post a Comment for "Make List To String Python"