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 like this :
data=[['data1'],['data2'],['data3']]
list=" ".join(data)
But get error like this :
string= " ".join(data)
TypeError: sequence item 0: expected string, list found
Can somebody help me?
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.
Have you tried?
data=[['data1'],['data2'],['data3']]
t = map(lambda x : str(x), data)
print(" ".join(t))
Live demo - https://repl.it/BOaS
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]'
>>> import re
>>> l = [['data1'], ['data2'], ['data3']]
>>> s = ""
>>> for i in l:
s+= re.sub(r"\'", "", str(i))
>>> s
'[data1][data2][data3]'
How about this?
data = [['data1'], ['data2'], ['data3']]
result = " ".join('[' + a[0] + ']' for a in data)
print(result)
How about this:
In [13]: a = [['data1'],['data2'],['data3']]
In [14]: import json
In [15]: temp = " ".join([json.dumps(x) for x in a]).replace("\"", "")
In [16]: temp
Out[16]: '[data1] [data2] [data3]'
Try the following. This can also be achieved by "Reduce":
from functools import reduce
data = [['data1'], ['data2'], ['data3']]
print(list(reduce(lambda x,y : x+y, data)))
output: ['data1', 'data2', 'data3']
Related
I've array of string in python, I'm iterating over the loop each value and trying to append ('|') symbol using below code. But its not appending as expected
result_list = []
new_value = 'iek,33833,,sdfd,lope'
my_list = ['abc,1234,,ickd,sold', 'yeje,38393,,dkdi,eole', 'euei,38393,,idkd,dikd']
for val in my_list:
result_list.append(val + '|')
res = result_list.append(new_value) + '|')
print res
I'm trying to print the list of string including new string at last. But its giving me below error:
TypeError: can only concatenate list (not "str") to list
Sample output:
abc,1234,,ickd,sold|yeje,38393,,dkdi,eole|euei,38393,,idkd,dikd|iek,33833,,sdfd,lope|
Thanks a lot for your help!
Use a list comprehension to add |, then join():
''.join([x+'|' for x in my_list])
# abc,1234,,ickd,sold|yeje,38393,,dkdi,eole|euei,38393,,idkd,dikd|
Simply using '|'.join() won't get you the final | you require.
This will directly give you the result.
'|'.join(my_list) + '|'
No need to iterate, you can use join() to achieve this.
my_list = ['abc,1234,,ickd,sold', 'yeje,38393,,dkdi,eole', 'euei,38393,,idkd,dikd']
print '|'.join(my_list)
output:
abc,1234,,ickd,sold|yeje,38393,,dkdi,eole|euei,38393,,idkd,dikd
result_list = []
my_list = ['abc,1234,,ickd,sold', 'yeje,38393,,dkdi,eole', 'euei,38393,,idkd,dikd']
for val in my_list:
result_list.append(str(val)+"|")
# result_list.append()
print ''.join(result_list)
I would like to separate my string every both commas but I can not, can you help me.
This is what I want: ['nb1,nb2','nb3,nb4','nb5,nb6']
Here is what I did :
a= 'nb1,nb2,nb3,nb4,nb5,nb6'
compteur=0
for i in a:
if i==',' :
compteur+=1
if compteur%2==0:
print compteur
test = a.split(',', compteur%2==0 )
print a
print test
The result:
2
4
nb1,nb2,nb3,nb4,nb5,nb6
['nb1', 'nb2,nb3,nb4,nb5,nb6']
Thanks you by advances for you answers
You can use regex
In [12]: re.findall(r'([\w]+,[\w]+)', 'nb1,nb2,nb3,nb4,nb5,nb6')
Out[12]: ['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
A quick fix could be to simply first separate the elements by commas and then join the elements by two together again. Like:
sub_result = a.split(',')
result = [','.join(sub_result[i:i+2]) for i in range(0,len(sub_result),2)]
This gives:
>>> result
['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
This will also work if the number of elements is odd. For example:
>>> a = 'nb1,nb2,nb3,nb4,nb5,nb6,nb7'
>>> sub_result = a.split(',')
>>> result = [','.join(sub_result[i:i+2]) for i in range(0,len(sub_result),2)]
>>> result
['nb1,nb2', 'nb3,nb4', 'nb5,nb6', 'nb7']
You use a zip operation of the list with itself to create pairs:
a = 'nb1,nb2,nb3,nb4,nb5,nb6'
parts = a.split(',')
# parts = ['nb1', 'nb2', 'nb3', 'nb4', 'nb5', 'nb6']
pairs = list(zip(parts, parts[1:]))
# pairs = [('nb1', 'nb2'), ('nb2', 'nb3'), ('nb3', 'nb4'), ('nb4', 'nb5'), ('nb5', 'nb6')]
Now you can simply join every other pair again for your output:
list(map(','.join, pairs[::2]))
# ['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
Split the string by comma first, then apply the common idiom to partition an interable into sub-sequences of length n (where n is 2 in your case) with zip.
>>> s = 'nb1,nb2,nb3,nb4,nb5,nb6'
>>> [','.join(x) for x in zip(*[iter(s.split(','))]*2)]
['nb1,nb2', 'nb3,nb4', 'nb5,nb6']
I have a question to print values in list.
import time
strings = time.strftime("%Y,%m,%d")
t = strings.split(',')
date = [int(x) for x in t]
print date
then result is
[2016,5,15]
But I want to print values in date like this
20160515
How can I fix it?
What's wrong with doing it like this:
>>> strings = time.strftime("%Y%m%d")
>>> strings
'20160515'
you must just change your code :
import time
strings = time.strftime("%Y%m%d") # delete ','
print strings
Why don't just do:
time.strftime("%Y%m%d")
On the other hand, if you are just looking for a way to concatenate elements of a list, use join:
In [110]: s = time.strftime("%Y,%m,%d")
In [111]: sl = s.split(',')
In [112]: ''.join(sl)
Out[112]: '20160515'
How do I concatenate a list of strings into a single string?
For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?
For handling a few strings in separate variables, see How do I append one string to another in Python?.
For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.
Use str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
A more generic way (covering also lists of numbers) to convert a list to a string would be:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
It's very useful for beginners to know
why join is a string method.
It's very strange at the beginning, but very useful after this.
The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).
.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).
Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
Edit from the future: Please don't use the answer below. This function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.
Although #Burhan Khalid's answer is good, I think it's more understandable like this:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
The second argument to join() is optional and defaults to " ".
list_abc = ['aaa', 'bbb', 'ccc']
string = ''.join(list_abc)
print(string)
>>> aaabbbccc
string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc
string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc
string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc
We can also use Python's reduce function:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
We can specify how we join the string. Instead of '-', we can use ' ':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
If you have a mixed content list and want to stringify it, here is one way:
Consider this list:
>>> aa
[None, 10, 'hello']
Convert it to string:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
If required, convert back to the list:
>>> ast.literal_eval(st)
[None, 10, 'hello']
If you want to generate a string of strings separated by commas in final result, you can use something like this:
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
Without .join() method you can use this method:
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.
Consider this Python code for printing a list of comma separated values
for element in list:
print element + ",",
What is the preferred method for printing such that a comma does not appear if element is the final element in the list.
ex
a = [1, 2, 3]
for element in a
print str(element) +",",
output
1,2,3,
desired
1,2,3
>>> ','.join(map(str,a))
'1,2,3'
A ','.join as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don't see in any of the answers so far, is
print ','.join(str(x) for x in a)
known as a generator expression or genexp.
If you prefer a loop (or need one for other purposes, if you're doing more than just printing on each item, for example), there are of course also excellent alternatives:
for i, x in enumerate(a):
if i: print ',' + str(x),
else: print str(x),
this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma before each item but the first. A last-time switch is slightly less elegant and it work only for iterables which have a len() (not for completely general ones):
for i, x in enumerate(a):
if i == len(a) - 1: print str(x)
else: print str(x) + ',',
this example also takes advantage of the last-time switch to terminate the line when it's printing the very last item.
The enumerate built-in function is very often useful, and well worth keeping in mind!
It's very easy:
print(*a, sep=',')
Print lists in Python (4 Different Ways)
There are two options ,
You can directly print the answer using
print(*a, sep=',')
this will use separator as "," you will get the answer as ,
1,2,3
and another option is ,
print(','.join(str(x) for x in list(a)))
this will iterate the list and print the (a) and print the output as
1,2,3
That's what join is for.
','.join([str(elem) for elem in a])
print ','.join(a)
def stringTokenizer(sentense,delimiters):
list=[]
word=""
isInWord=False
for ch in sentense:
if ch in delimiters:
if isInWord: # start ow word
print(word)
list.append(word)
isInWord=False
else:
if not isInWord: # end of word
word=""
isInWord=True
word=word+ch
if isInWord: # end of word at end of sentence
print(word)
list.append(word)
isInWord=False
return list
print (stringTokenizer(u"привет парни! я вам стихами, может быть, еще отвечу",", !"))
>>> a=[1,2,3]
>>> a=[str(i) for i in a ]
>>> s=a[0]
>>> for i in a[1:-1]: s="%s,%s"%(s,i)
...
>>> s=s+","+a[-1]
>>> s
'1,2,3'