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

得到以下錯誤:

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]

使用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 = "abc 123 $$%%"
>>> map(int,filter(str.isdigit,s.split()))
[123]

解釋:

  • s.split()在空格上拆分字符串並生成: ['abc', '123', '$$%%']
  • str.isdigit是一個函數,如果參數中的所有字符都是數字,則返回True
  • filter過濾掉列表中未通過測試的元素。 第一個參數是測試函數: str.isdigit ,第二個參數是列表。
  • 最后, map將一個列表轉換為另一個列表。 第一個參數是轉換函數int ,第二個參數是從filter找到的列表。

嘗試這個

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

輸出
['abc', '123', '$$%%']
不是數字
這是一個數字
不是數字

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

試試這個代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM