要在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")