Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要在python中搜索给定字符串中的数值吗_Python - Fatal编程技术网

要在python中搜索给定字符串中的数值吗

要在python中搜索给定字符串中的数值吗,python,Python,获取以下错误: string3 = "abc 123 $$%%" list1 = string3.split() print(list1) for i in list1: if int(i) > 0: print("it's a number") else: print("not a number") 使用i.isdigit() 奇特的方式: string3 = "abc 123 $$%%" list1 = string3.split(

获取以下错误:

string3 = "abc 123 $$%%"

list1 = string3.split()
print(list1)
for i in list1:
    if int(i) > 0:
        print("it's a number")
    else:
        print("not a number")
使用i.isdigit()

奇特的方式:

string3 = "abc 123 $$%%"

list1 = string3.split() 
print(list1)
for i in list1:
    if i.isdigit():
        print("it's a number") 
    else: 
        print("not a number")
说明:

  • s.split()
  • str.isdigit
    是一个函数,如果参数中的所有字符都是数字,则返回
    True
  • filter
    筛选列表中未通过测试的元素。第一 参数是测试函数:
    str.isdigit
    ,第二个参数是列表
  • 最后,
    map
    将一个列表转换为另一个列表。第一个参数是变换函数
    int
    ,第二个参数是从
    过滤器中找到的列表

试试这个

>>> s = "abc 123 $$%%"
>>> map(int,filter(str.isdigit,s.split()))
[123]
输出
['abc','123','$$%%']
不是一个数字
这是一个数字
不是数字

string3 = "abc 123 $$%%"

list1 = string3.split()
print(list1)
for i in list1:
    if i.isdigit():
        print("it's a number")
    else:
        print("not a number")
尝试此代码

您认为
int('$$%%')
应该返回什么?可能存在重复的
>>> s = "abc 123 $$%%"
>>> map(int,filter(str.isdigit,s.split()))
[123]
string3 = "abc 123 $$%%"

list1 = string3.split()
print(list1)
for i in list1:
    if i.isdigit():
        print("it's a number")
    else:
        print("not a number")
string3 = "abc 123 $$%%"

list1 = string3.split()
print(list1)
for i in list1:
    try:
        int(i)
        print("It is a number")
    except ValueError:
        print("It is not a number")