-2

Given a Python string such as:

"good \nand bad and\n\t not great and awesome"

I want to split this into an array on the ands, while also removing the stray \n's and \t's:

["good", "bad", "not great", "awesome"]

How to do so with re.split()?

Winston
  • 55
  • 5
  • 1
    Does this answer your question? [How to split a string into a list?](https://stackoverflow.com/questions/743806/how-to-split-a-string-into-a-list) – sushanth Nov 02 '21 at 05:13
  • 1
    Followed by [``How to remove \n from a list element?``](https://stackoverflow.com/a/3849519/4985099) – sushanth Nov 02 '21 at 05:14

2 Answers2

2

Here is a regex split approach. We can try splitting on \s+and\s+, which will target and surrounded by whitespace on both sides. Note that tabs and newlines are whitespace characters and are included by \s.

inp = "good \nand bad and\n\t not great and awesome"
parts = re.split(r'\s+and\s+', inp)
print(parts)  # ['good', 'bad', 'not great', 'awesome']
Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318
0

You can try this out.

s = "good \nand bad and\n\t not great and awesome"
s = s.replace('\n','').replace('\t','')
s_list = s.split('and')