-2

I have a problem with a Python string. Given a Python string with escape characters 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, such as below:

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

Is it possible to perform this in a single line with re.split()?

Winston
  • 61
  • 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
  • 502,043
  • 27
  • 286
  • 360
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')
Hasidul Islam
  • 324
  • 3
  • 12