【问题标题】:Separate digits from text in Python在 Python 中将数字与文本分开
【发布时间】:2020-10-27 20:05:49
【问题描述】:

我正在尝试将数字与 Python 中的字符串分开,例如以下示例:

text = "Compute the average of 5,7". (I want to get a list [5,7])

(数字之间的逗号是必须的)我试过使用:

numbers = [int(i) for i in text.split() if i.isdigit()]

当数字没有用逗号分隔时,它可以工作,但用逗号书写时,我只会收到一个空列表。

【问题讨论】:

  • 也许你可以使用:numbers = [int(i) for i in text if i.isdigit()]
  • 5,7 不是整数
  • 顺便问一下,你想要数字还是真的需要逗号?
  • @DaniMesejo 他说他想要一份数字列表。
  • @Barmar 那么用于提取数字的简单正则表达式应该足够了吧?

标签: python string list split numbers


【解决方案1】:

使用正则表达式查找以逗号分隔的两个整数。

import re

m = re.search(r'(\d+),(\d+)', text)
if m:
    numbers = [int(x) for x in m.groups()]

【讨论】:

  • 作为扩展,考虑re.findall() 并测试是否找到比预期更多的组
【解决方案2】:

试试这个:

text = "Compute the average of 5,7"
nums = [int(i) for i in text if i.isdigit()]
print(nums)
# prints [5, 7]

【讨论】:

  • 但是,OP 要求 digits 被分隔。
【解决方案3】:
>>> import re
>>> re.search('.*(\d,\d).*', text).group(1)
'5,7'

【讨论】:

  • 你不需要.*
猜你喜欢
  • 2021-06-13
  • 2022-07-15
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 2015-04-21
  • 2023-04-01
  • 2019-04-13
  • 1970-01-01
相关资源
最近更新 更多