简体   繁体   中英

Python split string at comma, ignore comma in numbers

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?

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); 

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

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

line_2 = line_1.split(', ')

print(line_2)

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