首页 > 解决方案 > 在 Python 中对数字使用 de startswith 函数

问题描述

我有一个带有数字和字符的列向量,如下所示:

Data
123456
789101
159482
Airplane
Car
Blue
159874

我只需要过滤数值。

我尝试使用该Data.int.startswith功能,但我相信这个功能不存在。

谢谢。

标签: python-3.xpython-2.7

解决方案


不确定您到底在问什么,但如果您的意思是要从字符串中过滤掉一个整数列表,您可以执行以下操作:

string = """Data
123456
789101
159482
Airplane
Car
Blue
159874""" #The data you provided

def isInt(s): #returns true if the string is an int
    try:
        int(s)
        return True
    except ValueError:
        return False

print( [i for i in string.splitlines() if isInt(i)] ) #Loop through the lines in the string, checking if they are integers.

这将返回以下列表:

[123456, 789101, 159482, 159874]

推荐阅读