-2

I have the details of an amazon order, the literal string is separated by the newline character \n.

str = 'Linon Hampton Stool Fabric Top, 24-inch \nSold by: Amazon.com Services, Inc \n$33.99'

I want to split it up into n number of strings for each new line so that it looks like.

str1 = 'Linon Hampton Stool Fabric Top, 24-inch'
str2 = 'Sold by: Amazon.com Services, Inc '
str3 = '$33.99'
geistmate
  • 525
  • 2
  • 5
  • 14
  • `str` is the built-in name of the string type. by using that name you could have many problems. use some other name, such as `multi_line_string` or `mystr`. – Skaperen Aug 04 '19 at 03:09

2 Answers2

0

Use split. It will give you output in the form of list:

string = 'Linon Hampton Stool Fabric Top, 24-inch \nSold by: Amazon.com Services, Inc \n$33.99'

string.split("\n")

And don't give your variables name str. Its a builtin function name.

Nouman
  • 6,947
  • 7
  • 32
  • 60
  • Yes you're right. I realized that shortly after I posted the example. I also realized assigning different variables is useless and I will just access them by accessing the list. Thank you very much for the help. – geistmate Aug 04 '19 at 02:21
  • the 2nd argument of .split() must be an `int`. it is the number of times to apply splitting. – Skaperen Aug 04 '19 at 03:18
  • @Skaperen Sorry! I misplaced `split` as `replace`. Fixed – Nouman Aug 04 '19 at 03:20
0

you can use mystr.splitlines(). the big difference is that you won't get an empty string at the end of the resulting list when mystr ends with '\n'.

Skaperen
  • 453
  • 4
  • 13