简体   繁体   English

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

[英]want to search a numeric value in given string in 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")

Getting below error :得到以下错误:

if int(i) > 0:
ValueError: invalid literal for int() with base 10: 'abc'
>>> str = "abc 123 $$%%"
>>> [int(s) for s in str.split() if s.isdigit()]
[123]

use i.isdigit()使用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")

Fancy way:花式方式:

>>> s = "abc 123 $$%%"
>>> map(int,filter(str.isdigit,s.split()))
[123]

Explanation:解释:

  • s.split() is splitting the string on spaces and generates: ['abc', '123', '$$%%'] s.split()在空格上拆分字符串并生成: ['abc', '123', '$$%%']
  • str.isdigit is a function which returns True if all characters in the argument are digits. str.isdigit是一个函数,如果参数中的所有字符都是数字,则返回True
  • filter filters out elements of a list which do not pass the test. filter过滤掉列表中未通过测试的元素。 First argument is the test function: str.isdigit , second argument is the list.第一个参数是测试函数: str.isdigit ,第二个参数是列表。
  • Finally, map transforms one list to another.最后, map将一个列表转换为另一个列表。 First argument is the transform function int , second argument is the list found from filter .第一个参数是转换函数int ,第二个参数是从filter找到的列表。

try this尝试这个

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

Output :输出
['abc', '123', '$$%%'] ['abc', '123', '$$%%']
not a number不是数字
it's a number这是一个数字
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")

Try this code试试这个代码

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

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