EArwa
EArwa

Reputation: 53

How do I join individual elements into a list of strings in Python

I have a list of lists, say y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]] I want to convert each of the inner lists into a strings separated by '/' and output a list of the individual strings. How can I do this in python?

Upvotes: 1

Views: 861

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22472

You could use str.join after mapping the ints to strings within a list comprehension:

>>> y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]
>>> formatted_y = ['/'.join(map(str, inner_list)) for inner_list in y]
>>> formatted_y
['2/4/6/7', '9/0/8/12', '1/11/10/5']

Or if you prefer you could use a couple of nested list comprehensions:

>>> formatted_y = ['/'.join(str(x) for x in inner_list) for inner_list in y]
>>> formatted_y
['2/4/6/7', '9/0/8/12', '1/11/10/5']

To go back to the original you can use str.split within a list compression:

>>> original_y = [list(map(int, inner_str.split('/'))) for inner_str in formatted_y]
>>> original_y
[[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]

Upvotes: 1

bart
bart

Reputation: 1048

y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]
myNewList = []
for myList in y:
    myMap = map(str,myList)

map(function, iterable) is used to apply a function ('str' in this case) to all elements of a specified iterable ('myList').

    myString = '/'.join(myMap)

join(iterable) returns a string which is the concatenation of the strings in iterable. The separator between elements is the string providing this method.

    myNewList.append(myString)

list.append(elem) appends an element to the end of the list.

print(myNewList)

['2/4/6/7', '9/0/8/12', '1/11/10/5']

Upvotes: 1

Related Questions