简体   繁体   English

在Python中的字符串中搜索数字

[英]Search string for digits in Python

I have a list of strings that contain letters and numbers. 我有一个包含字母和数字的字符串列表。 I want to search for the numbers and have them returned to me. 我想搜索这些号码并将它们退还给我。 What is the best way to do this? 做这个的最好方式是什么? I'm pretty new to Python and I looked into regular expressions and I'm in the process of learning them now, but I don't know when I'll be good enough in regular expressions before I can use them. 我对Python还是很陌生,我研究了正则表达式,现在正在学习它们,但是我不知道何时可以使用正则表达式就足够了。

To return all numbers in all strings in a list named inputlist , you can use a list comprehension: 要返回名为inputlist的列表中所有字符串的所有数字,可以使用列表inputlist

import re

numbers = [int(num) for value in inputlist for num in re.findall('\d+', value)]

This casts the numbers to integers as well. 这也将数字转换为整数。 If you needed floating point values (so, numbers with a decimal point in them), add on a pattern for one decimal point flanked by digits: 如果您需要浮点值(所以,在他们小数点的数字),加上由数字两侧小数点后一位数的模式:

numbers = [float(num) for value in inputlist for num in re.findall('\d+(?:\.\d*)', value)]

If, however, you are only looking for strings that are numbers (rather than just contain numbers), str.isdigit() may suffice: 但是,如果你只是在寻找那些数字(而不是仅仅包含数字),字符串str.isdigit()可能就足够了:

numbers = [int(value) for value in inputlist if value.isdigit()]

Note that this will not match floating point numbers ( str.isdigit() is only True if all characters are digits; a decimal point doesn't count). 请注意,这将匹配浮点数(仅当所有字符均为数字时, str.isdigit()才为True ;小数点不计算在内)。

You can use isdigit : 您可以使用isdigit

numbers = [n for n in strings if n.isdigit()]

If you actually want to parse them: 如果您实际上想解析它们:

numbers = [int(n) for n in strings if n.isdigit()]

This is assuming that you only want the strings that are all digits, and you will want to ignore strings that are mixed letters and numbers. 这是假设您只希望使用数字的字符串,而您将要忽略字母和数字混合的字符串。 Unfortunately, it's unclear from your question which you actually want. 不幸的是,从您的问题中不清楚您真正想要的是什么。 You also didn't specify whether or not the numbers represent integers, or they might representing floating-point values. 您也没有指定数字是否表示整数,否则它们可能表示浮点值。 :-( :-(

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

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