简体   繁体   English

如何从字符串列表中提取数字

[英]How to extract numbers from list of strings

List1 = ["rob12is34","jimmy56is78"]

I want output as我想要 output 作为

Output = ["1234","5678"]

If you gave an answer then please explain it如果您给出了答案,请解释一下

With a regex and re.sub :使用正则表达式和re.sub

List1 = ["rob12is34","jimmy56is78"]

import re

out = [re.sub(r'\D', '', s) for s in List1]

output: ['1234', '5678'] output: ['1234', '5678']

Since its a list, loop the list first:由于它是一个列表,因此首先循环列表:

for item in List1:
    item

Then find all the numbers from it.然后从中找出所有的数字。 To do it, loop the string and find all the digits from it.为此,请循环字符串并从中查找所有数字。

output = []
from item in List1:
    digit_string = ''
    for character in item:
        if character.isdigit():
            digit_string += character

    # Then add the digit_string to your list
    output.append(digit_string)
print(output)
for item in List1:
    print("".join([x for x in item if x in "0123456789"]))

If you could use Regex如果你可以使用正则表达式

import re

List1 = ["rob12is34","jimmy56is78"]
for s in List1:
    print(''.join(re.findall('\d+', s)))

1234
5678

using filter:使用过滤器:

List1 = ["rob12is34", "jimmy56is78"]
result = []
for i in List1:
   result.append(''.join(filter(str.isdigit, i)))

print(result)
>>>> ['1234', '5678']

Here's a compact solution with a list comprehension:这是一个带有列表理解的紧凑解决方案:

List1 = ["rob12is34","jimmy56is78"]

["".join(filter(str.isdigit, text)) for text in List1]

>>> ['1234', '5678']

Sharing another way to solve your problem:分享另一种解决问题的方法:

List1 = ["rob12is34","jimmy56is78"] List1 = ["rob12is34","jimmy56is78"]

output_list = []
for item in List1:
    for s in item:
        if not s.isdigit():
            item = item.replace(s, "")
    output_list.append(item)

output_list ['1234', '5678'] output_list ['1234', '5678']

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

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