0

I have an array that looks something like this:

arr1 = ["1", "2", "3 4", "5 6 7", "8"]

and I want to, somehow, split the strings with spaces in them turning this array into this:

split_arr1 = ["1", "2", "3", "4", "5", "6", "7", "8"]

Note: The split array does not have to be in order

Thank you!

3 Answers 3

1

Iterating the input list and using split:

arr1 = ["1", "2", "3 4", "5 6 7", "8"]
output = []
for item in arr1:
    output.extend(item.split())

print(output)  # ['1', '2', '3', '4', '5', '6', '7', '8']

For each entry in the input list we call extend on some output list (initially empty). This will add each element from splitting e.g. "5 6 7" as a new separate entry in the output list.

Sign up to request clarification or add additional context in comments.

1 Comment

@wl2776 That won't work, because a list comprehension is using append under the hood, while we need extend here (hence my explicit loop). Though I would prefer to also use a list comprehension.
1

You could do this using nested list comprehension:

arr1 = ["1", "2", "3 4", "5 6 7", "8"]

split_arr1 = [split_item for item in arr1 for split_item in item.split()]
# ['1', '2', '3', '4', '5', '6', '7', '8']

Comments

0

A very simple solution:

arr1 = ["1", "2", "3 4", "5 6 7", "8"]

split_arr1 = list("".join(arr1).replace(" ", ""))

Explanation:

  1. Join all strings into one string -> "123 45 6 78"
  2. Remove any white spaces -> "12345678"
  3. Split each character -> ['1', '2', '3', '4', '5', '6', '7', '8']

2 Comments

What if original array would have strings longer than one character?
well, i am assuming that its single digits as per his example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.