當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python String isnumeric()用法及代碼示例


Python String isnumeric() 方法是用於字符串處理的 內置 方法。如果字符串中的所有字符都是數字字符,則 issnumeric() 方法返回 “True”,否則返回 “False”。此函數用於檢查參數是否包含所有數字字符,如整數、分數、下標、上標、羅馬數字等(均以 Unicode 編寫)

Syntax: 

string.isnumeric()

參數:

isnumeric() does not take any parameters



返回:

  • True - If all characters in the string are numeric characters.
  • False - If the string contains 1 or more non-numeric characters.

Errors and Exceptions:

  1. It does not contain any arguments, therefore, it returns an error if a parameter is passed.
  2. Whitespaces are not considered to be numeric, therefore, it returns “False”
  3. Subscript, Superscript, Fractions, Roman numerals (all written in Unicode)are all considered to be numeric, Therefore, it returns “True”

範例1:

Input:string = '1889345'
Output:True

Input:string = '\u00BD'
Output:True

Input:string = '123ayu456'
Output:False

Python3


# Python code for implementation of isnumeric()
    
# checking for numeric characters
string = '123ayu456'
print(string.isnumeric())
   
string = '123456'
print( string.isnumeric())

輸出:

False
True

範例2:

應用:python中給定一個字符串,計算字符串中數字字符的個數並從字符串中刪除,並打印出字符串。

Input:string = '123geeks456for789geeks'
Output:9
         geeksforgeeks

Input:string = '123ayu456'
Output:6
         ayu

算法:

  1. 將一個空的 NewString 和變量 count 初始化為 0。
  2. 逐個字符遍曆給定的字符串直到其長度,檢查該字符是否為數字字符。
  3. 如果是數字字符,計數器加1,不加到新字符串,否則遍曆下一個字符,如果不是數字,繼續加到新字符串。
  4. 打印計數器的值和 NewString。

Python3


# Python implementation to count numeric characters
# in a string and print non numeric characters
# Given string
# Initialising the counter to 0
string ='123geeks456for789geeks'
count = 0
  
newstring1 =""
newstring2 =""
    
# Iterating the string and checking for numeric characters
# Incrementing the counter if a numeric character is found
# And adding the character to new string if not numeric
# Finally printing the count and the newstring
for a in string:
    if (a.isnumeric()) == True:
        count+= 1
    else:
        newstring1+= a
print(count)
print(newstring1)
   
string ='123ayu456'
count = 0
for a in string:
    if (a.isnumeric()) == True:
        count+= 1
    else:
        newstring2+= a
print(count)
print(newstring2)

輸出:

9
geeksforgeeks
6
ayu




相關用法


注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 Python String isnumeric() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。