-1

The strip command does not work on a list that contains other lists. E.g. [ “ one”,”two “,[ “four”,”five”]] I want to print out the words without the [].

Is there a way to get around this?

It turns out I was using append to build a list from other lists. I have now used the extend command instead to build the list which dispenses with the [] brackets, so printing is now straightforward. The extend command was not one I was familiar with before.

Davy Cotton
  • 69
  • 1
  • 1
  • 4

3 Answers3

0

It's not entirely clear what you are trying to achieve, but if you just want to have a string representation without square brackets, you can do this:

l = [..., [...]]
s =str(l).replace("[", ""). replace("]", "")
print(s)

Mind that this can be misleading in many cases, because a list element that is a list of list looks like multiple string-type list elements. So you might want to reconsider why you want to do that.

Carsten
  • 1,912
  • 1
  • 28
  • 55
0

Your [ and ] are forming a list, in your example a nested list.
You could use a recursive function to print it all out:

lst = [' one', 'two ', ['four', 'five']]

def recursive_print(my_list):
    for item in my_list:
        if isinstance(item, list):
            recursive_print(item)
        else:
            print(item.strip())

recursive_print(lst)

This yields

one
two
four
five

If you want to collect the stripped words, you could use

def recursive_yield(my_list):
    for item in my_list:
        if isinstance(item, list):
            yield from recursive_yield(item)
        else:
            yield item.strip()

flattened = [word for word in recursive_yield(lst)]
print(flattened)

Which would yield

['one', 'two', 'four', 'five']

Both functions will work for arbitrarily nested lists.

Jan
  • 42,290
  • 8
  • 54
  • 79
0
l=[ "one","two",[ "four","five"]]
for i in l:
    if(isinstance(i,list)):
        for j in i:
            print(j,end=' ');#sep by spaces
    else:
        print(i,end=' ');

output:

one two four five

viruchith
  • 51
  • 1
  • 8