【问题标题】:How can I split this comma-delimited string in Python? [duplicate]如何在 Python 中拆分这个逗号分隔的字符串? [复制]
【发布时间】:2011-08-17 09:28:01
【问题描述】:

嗨,我一直在阅读有关正则表达式的信息,我已经获得了一些基本的资源。我现在一直在尝试使用 Re 来整理这样的数据:

“144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008” P>

...进入一个元组,但我无法让它工作。

谁能解释一下他们将如何处理这样的事情?

谢谢

【问题讨论】:

  • “这样的数据”是什么意思?数字整数?有时有3位数?您尝试使用正则表达式捕获的模式是什么?
  • 我的意思是将每个用逗号隔开的整数分隔成一个列表。

标签: python regex string


【解决方案1】:

这里不需要正则表达式。

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

给你:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

【讨论】:

  • 如果是从文件中读取的,您将需要使用s.strip().split(',')。 strip 方法去掉了换行符和其他空格。
【解决方案2】:

列表怎么样?

mystring.split(",")

如果您能解释一下我们正在查看的信息类型可能会有所帮助。也许还有一些背景信息?

编辑:

我想你可能需要两人一组的信息?

然后试试:

re.split(r"\d*,\d*", mystring)

如果你想让它们变成元组

[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]

以更易读的形式:

mylist = []
for match in re.split(r"\d*,\d*", mystring):
    for pair in match.split(",")
        mylist.append((pair[0], pair[1]))

【讨论】:

    【解决方案3】:

    问题有点模糊。

    list_of_lines = multiple_lines.split("\n")
    for line in list_of_lines:
        list_of_items_in_line = line.split(",")
        first_int = int(list_of_items_in_line[0])
    

    等等

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 1970-01-01
      • 2012-05-24
      • 2023-04-09
      • 2011-07-13
      • 2018-12-21
      相关资源
      最近更新 更多