0

If I'm given the string

"Today, I picked, a total, of, 1,000,000, apples"

I want

[Today, I picked, a total, of, 1,000,000, apples] 

I tried using string.split(","), but that doesn't account for commas in numbers... Could you help me for this particular case? Thank you

Edit I previously asked this question for javascript, can anyone provide any insights for python?

Bob A.
  • 3
  • 1
  • 5

3 Answers3

2

You can be more specific by using a regular expression to ignore commas when next to numeric values.

var s = "Today, I picked, a total, of, 1,000,000, apples";

var a = s.split(/(?!\d)\,(?!\d)/);

console.log(a);
D.B.
  • 1,772
  • 1
  • 10
  • 13
  • Wow this is awesome!! Exactly what I'm looking for. I also tested this in the python language, how come with the same split parameter, it outputs differently? – Bob A. Dec 06 '17 at 23:27
1

replace your string.split(",") by string.split(", ") with a space after the comma. This should be enough to avoid splitting the numbers.

Allan
  • 11,650
  • 3
  • 27
  • 49
  • What if my original string is ""Today,I picked,a total,of,1,000,000,apples"? Is there a better way? – Bob A. Dec 06 '17 at 23:06
0

line_1 = "Today, I picked, a total, of, 1,000,000, apples"

line_2 = line_1.split(', ')

print(line_2)

arpit patel
  • 121
  • 1
  • 2
  • Code only answers can almost always be improved by explaining what the code does and why it does it. In this case that space after the comma could be called out as it is easy to miss. Also the code should be formatted as code using the "{}" button or other formatting methods. – Jason Aller Sep 12 '19 at 15:48