简体   繁体   中英

Splitting lists and retaining the spaces in python

I want to split this list called shape:

shape = '\n'.join(["+------------+",
                   "|            |",
                   "|            |",
                   "|            |",
                   "+------+-----+",
                   "|      |     |",
                   "|      |     |",
                   "+------+-----+"])

It should return something like:

['+------------+',|           |, |            |,'+------+-----+',...]

And not

    ['+------------+', '|', '|', '|', '|', '|', '|', '+------+-----+', '|', '|', '|', '|', '|', '|', '+------+-----+']

I have tried using split() but it was to no avail.

Thank you for your time!

Edit: fixed the formatting, its been 7 years since I last used stackoverflow xD

I assume the "list" you want to split is not a list but a list-like string.

You can do this:

l = ["| |", '| |',"| |",    "| |"]

stringified_list = str(l)

stringified_list = stringified_list.strip("[")
stringified_list = stringified_list.strip("]")
stringified_list = stringified_list.replace("'", "")

print(stringified_list)
>>> | |, | |, | |

For your new question, it looks like you want to split the string on the newline character, use:

lines = shape.split("\n")
print(lines)
>>> ['+------------+', '|            |', '|            |', '|            |', '+------+-----+', '|      |     |', '|      |     |', '+------+-----+']

To make it "return something like this":

[| |, | |]

Use further processing:

stringified_lines = str(lines)

stringified_lines = stringified_lines.replace("'", "")
print(stringified_lines)
>>> [+------------+, |            |, |            |, |            |, +------+-----+, |      |     |, |      |     |, +------+-----+]

Try this:

liste = ['||', '||']
print(*liste)
>>> || ||

it should work

I assume you are just stripping the leading spaces. Here is a one liner:

print([line.strip() for line in shape.split("\n")])

Output:

['+------------+', '|            |', '|            |', '|            |', '+------+-----+', '|      |     |', '|      |     |', '+------+-----+']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM