简体   繁体   English

Python在逗号处分割字符串,忽略数字逗号

[英]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? 我尝试使用string.split(",") ,但是这不能解决数字中的逗号...在这种情况下,您能帮我吗? Thank you 谢谢

Edit I previously asked this question for javascript, can anyone provide any insights for python? 编辑我之前曾问过这个关于javascript的问题,谁能为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. string.split(",")替换为string.split(", ")并在逗号后加一个空格。 This should be enough to avoid splitting the numbers. 这应该足以避免拆分数字。

line_1 = "Today, I picked, a total, of, 1,000,000, apples" line_1 =“今天,我总共采摘了1,000,000个苹果”

line_2 = line_1.split(', ') line_2 = line_1.split(',')

print(line_2) 打印(第_2行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM