Convert a Python list of lists to a single string - python

I have list of lists consisting of chars and integers like this:
list = [[65], [119, 'e', 's', 'i'], [111, 'd', 'l'], [111, 'l', 'w'], [108, 'd', 'v', 'e', 'i'], [105, 'n'], [97, 'n'], ['111', 'k', 'a']]
I want to convert this into a single string like this:
"65 119esi 111dl 111lw 108dvei 105n 97n 111ka"
I have tried this:
new_list = [' '.join(x for x in list)]
but it is giving me this error:
TypeError: sequence item 0: expected str instance, list found
So what am i supposed to do, I'm new to coding!

That error you get is because .join() expects strings to join together, but you are passing it a list instead (one of the subarrays).
A one liner would be:
" ".join(["".join([str(item) for item in sublist]) for sublist in your_list])
Note that this only works for one level of nested arrays. If you had more or indefinite, probably its better to write your own function that does the job.

To make it a bit easier to see what is happening you could use:
final_string = ""
for elem in list:
final_string = final_string + " "
for el in elem:
final_string = final_string +str(el)

You have ints in your sublists aswell, that need converting before joining. You can do the following, using map to do the string conversion of the tokens and str.join to piece them together:
lst = [[65], [119, 'e', ... ] # do NOT call a variable "list"
new_lst = " ".join("".join(map(str, sub)) for sub in lst)
# '65 119esi 111dl 111lw 108dvei 105n 97n 111ka'

Related

How to merge 2d array into string in python

I have tried this solution but the problem I am facing is that when I want to convert
[[65, 'D', 'M', 'A', 'H'], [65, 'S', 'I', 'N']]
to string using the method above , what i get is
'65DMAH65SIN'
but what I want is
'65DMAH 65SIN'
i.e after every array ends, it gives me space. I am thinking of logics for this but not working.
I would use following comprehension for that task:
a = [[65, 'D', 'M', 'A', 'H'], [65, 'S', 'I', 'N']]
s = ' '.join(''.join(map(str,i)) for i in a)
print(s)
Output:
65DMAH 65SIN
For every sublist I map it, so every element of sublist become str, then I join elements of every sublist without separator (empty str), which then I join using space.
Your problem answer is:
def solution(List):
result = ''
for i in range(len(string)):
for j in string[i]:
result+=str(j)
result+=' '
return result

Split words in string into nested lists of characters

Can anyone help me with a list comprehension to split a string into a nested list of words and characters? i.e:
mystring = "this is a string"
Wanted ouput:
[['t','h','i','s'],['i','s'],['a'],['s','t','r','i','n','g']]
I've tried the following, but it doesnt split 'x' into nested list:
mylist = [x.split() for x in mystring.split(' ')]
print(mylist)
[['this'],['is'],['a'],['string']]
[list(x) for x in mystring.split(' ')]
You can use a nested list comprehension:
[[j for j in i] for i in mystring.split()]
Yields:
[['t', 'h', 'i', 's'], ['i', 's'], ['a'], ['s', 't', 'r', 'i', 'n', 'g']]
You need list(x) instead of x.split():
[list(x) for x in mystring.split()]
Slightly similar to other answers
map(list,mystring.split(" "))

Python: Joining characters in sublists of list of lists

I have a huge list of lists, this is a section of it:
[['cusA', 'zupT', 'rcnA', 'cusA', 'zupT', 'zupT']]
I did the following operation on the entire list of lists:
[list(x) for x in set(tuple(x) for x in my_list)]
because I would like to have unique information in the sublists. This returned the following:
[['c', 'u', 's', 'A'], ['r', 'c', 'n', 'A'], ['z', 'u', 'p', 'T']]
Which is great, since it did become unique, but now I need them to be in their original from, without being broken up character-by-character.
Is there any way to re-join them inside the sublists?
Instead of list(x), use ''.join(x).
But you can just put the strings themselves in a set instead of calling tuple: list(set(my_list)).
If the ordering of the contents of the inner lists does not matter, you can turn them into a set, which is a an un-ordered collection of unique elements, and then turn that set back into a list:
result = [list(set(li)) for li in my_list]
Prints:
[['cusA', 'rcnA', 'zupT']]
as you already mentioned: you can join the strings:
print(''.join(['c', 'u', 's', 'A'])) # cusA
for your whole list you could do this:
lst = [['c', 'u', 's', 'A'], ['r', 'c', 'n', 'A'], ['z', 'u', 'p', 'T']]
str_lst = [''.join(item) for item in lst]
print(str_lst) # ['cusA', 'rcnA', 'zupT']
note that there is no point in creating a list of single characters; a string itself behaves exactly like a list of characters (an immutable one, though); so you could directoy do this:
print(set(['cusA', 'zupT', 'rcnA', 'cusA', 'zupT', 'zupT']))
# {'zupT', 'cusA', 'rcnA'}
# if you need a list again instead of a set:
print(list(set(['cusA', 'zupT', 'rcnA', 'cusA', 'zupT', 'zupT'])))
# ['zupT', 'cusA', 'rcnA']
that will not preserve the order though...

Split the word by each character python 3.5 [duplicate]

This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 2 years ago.
I tried using all the methods suggested by others but its not working.
methods like str.split(), lst = list("abcd") but its throwing error saying [TypeError: 'list' object is not callable]
I want to convert string to list for each character in the word
input str= "abc" should give list = ['a','b','c']
I want to get the characters of the str in form of list
output - ['a','b','c','d','e','f'] but its giving ['abcdef']
str = "abcdef"
l = str.split()
print l
First, don't use list as a variable name. It will prevent you from doing what you want, because it will shadow the list class name.
You can do this by simply constructing a list from the string:
l = list('abcedf')
sets l to the list ['a', 'b', 'c', 'e', 'd', 'f']
First of all, don't use list as name of the variable in your program. It is a defined keyword in python and it is not a good practice.
If you had,
str = 'a b c d e f g'
then,
list = str.split()
print list
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Since split by default will work on spaces, it Will give what you need.
In your case, you can just use,
print list(s)
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Q. "I want to convert string to list for each character in the word"
A. You can use a simple list comprehension.
Input:
new_str = "abcdef"
[character for character in new_str]
Output:
['a', 'b', 'c', 'd', 'e', 'f']
Just use a for loop.
input:::
str="abc"
li=[]
for i in str:
li.append(i)
print(li)
#use list function instead of for loop
print(list(str))
output:::
["a","b","c"]
["a","b","c"]

Simple Python List Concatenation

I have a list of strings, with each string as a character. They're in order of the word. How do I put each character all together in one string. Example:
list_characters = ['H', 'e', 'l', 'l', 'o']
To become:
'Hello'
Please help and thank you
In [1]: s = ['H', 'e', 'l', 'l', 'o']
In [2]: ''.join(s)
Out[2]: 'Hello'
The join method is a bit different from others you may be familiar with in that you put the element you want to use to 'join` the elements together first, and then call the method on that. Here are some more examples:
In [4]: print '\n'.join(s)
H
e
l
l
o
In [5]: ' '.join(s)
Out[5]: 'H e l l o'
In [6]: 'GOODBYE'.join(s)
Out[6]: 'HGOODBYEeGOODBYElGOODBYElGOODBYEo'
The join method accepts any 'iterable', which is anything you can 'iterate' over (such as a list, as in your example). Strings themselves are also iterables, so you could even do this:
In [7]: s = 'Hello'
In [8]: 'Z'.join(s)
Out[8]: 'HZeZlZlZo'
Although I highly recommend the join() method as mentioned by RocketDonkey above, another way would be this:
reduce(lambda acc,x:acc+x,['H', 'e', 'l', 'l', 'o'])
You need to use join() to concatenate all the elements of list into a string like this:
test = ['H', 'e', 'l' 'l', 'o']
''.join(test)
If you want to join with '-' character in between them, use this:
test = ['H', 'e', 'l' 'l', 'o']
'-'.join(test)
You can join the elements of list into a string by various methods:
By iterating through the list
str=""
for i in list:
str+=i
print(str) #hello
Using built in function 'join()'
list = ['h', 'e', 'l', 'l', 'o']
str=""
print("".join(list)) #hello
Using list comprehension
str = "".join([str(elem) for elem in list])
print(str) #hello
Using map() function
str = ''.join(map(str, list))
print(str) #hello
#Note: Last two methods can be used in case you have int elements also,
as Python doesn't allow concatenation of elements with different data types.

Categories