-2

I have a list of names split up letter by letter, I would like to concatenate the individual names together. This is what I currently have:

['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L', 'u', 'k', 'e', ' ', 'S', 'h', 'a', 'n', 'e', 'y', ' ', 'L', 'u', 'k', 'e', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'R', 'o', 'b', ' ']

I would like to turn it into this:

['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']
Shaney96
  • 75
  • 1
  • 9

4 Answers4

1

Let info be your list.

concat = "".join(info)
names = concat.split()
print names

But see the comment of Two-Bit Alchemist.

Alan
  • 9,410
  • 15
  • 20
1

Use itertools.groupby and group using str.isspace:

>>> from itertools import groupby
>>> lst = ['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L', 'u', 'k', 'e', ' ', 'S', 'h', 'a', 'n', 'e', 'y', ' ', 'L', 'u', 'k', 'e', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'M', 'o', 'l', 'e',  'y', ' ', 'R', 'o', 'b', ' ']
>>> [''.join(g) for k, g in groupby(lst, key=str.isspace) if not k]
['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']

I am reading from a text file. I broke up the text and placed it into a list, I'm now wondering how to get it so it recognizes when a space is present and it concatenates the data accordingly. I'm not sure how though

I am not sure how you read this text, but you're processing it incorrectly. Don't call list() on the line or the whole text you've read from the file:

>>> s = 'Stuart Steve Andrew Luke Shaney Luke Moley Moley Rob'
>>> list(s)
['S', 't', 'u', 'a', 'r', 't', ' ', 'S', 't', 'e', 'v', 'e', ' ', 'A', 'n', 'd', 'r', 'e', 'w', ' ', 'L', 'u', 'k', 'e', ' ', 'S', 'h', 'a', 'n', 'e', 'y', ' ', 'L', 'u', 'k', 'e', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'M', 'o', 'l', 'e', 'y', ' ', 'R', 'o', 'b']

If you want a list of words simply use str.split on the text you've read:

>>> s.split()
['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

You can iterate over the chars in the list, here is a little example:

# chars being your list
names = []

current_name = ""
for current_char in chars:
     if current_char == ' ':
         names.append(current_name)
         current_name = ""
     else:
          current_name += current_char

 return names
Marco
  • 330
  • 3
  • 12
0

Considering li to be the input list -

>>> [i for i in "".join(li).split(" ") if i.strip() != ""]
['Stuart', 'Steve', 'Andrew', 'Luke', 'Shaney', 'Luke', 'Moley', 'Moley', 'Rob']

The list comprehension is to just exclude empty strings.

Kamehameha
  • 5,423
  • 1
  • 23
  • 28