【问题标题】:Extract numeric values from a string for python从python的字符串中提取数值
【发布时间】:2019-07-17 13:45:17
【问题描述】:

我有一个字符串,其中包含引号内的数值。我需要从这些以及[] 中删除数值

示例字符串:texts = ['13007807', '13007779']

texts = ['13007807', '13007779'] 
texts.replace("'", "")
texts..strip("'")

print texts 

# this will return ['13007807', '13007779']

所以我需要从字符串中提取的是:

13007807
13007779

【问题讨论】:

  • 看起来你需要int()
  • 嗯...numbers = [int(s) for s in texts] 做你所追求的(给定你的样本)吗?还是texts 本身就是一个字符串?
  • texts 是我转换为字符串的列表 texts = str(re.findall(r"\d+", texts))

标签: python regex replace split


【解决方案1】:

如果您的 texts 变量是我从您的回复中了解到的字符串,那么您可以使用正则表达式:

import re
text = "['13007807', '13007779']"
regex=r"\['(\d+)', '(\d+)'\]"
values=re.search(regex, text)
if values:
    value1=int(values.group(1))
    value2=int(values.group(2))

输出:

值1=13007807

值2=13007779

【讨论】:

    【解决方案2】:

    你可以使用*解包操作符:

    texts = ['13007807', '13007779']
    print (*texts)
    

    输出:

    13007807 13007779
    

    如果你有:

    data = "['13007807', '13007779']"
    print (*eval(data))
    

    输出:

    13007807 13007779
    

    【讨论】:

      【解决方案3】:

      最简单的方法是使用map 并在list 中环绕

      list(map(int,texts))
      

      输出

      [13007807, 13007779]
      

      如果您的输入数据格式为data = "['13007807', '13007779']",则

      import re
      data = "['13007807', '13007779']"
      list(map(int, re.findall('(\d+)',data)))
      

      list(map(int, eval(data)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 2020-08-20
        相关资源
        最近更新 更多