如何檢查 Python 字串是否只包含數字?
要檢查 Python 字串是否只包含數字,我們可以使用內建的 isdigit() 方法。如果字串中的所有字元都是數字,則此方法返回 True,否則返回 False。
這是一個演示如何使用 isdigit() 的示例程式碼片段。
檢查字串是否只包含數字
示例
在這個例子中,我們首先定義一個名為 my_string 的字串,它只包含數字。然後我們使用 isdigit() 方法來檢查 my_string 是否只包含數字。由於它確實如此,因此輸出將為“字串只包含數字!”。
my_string = "1234"
if my_string.isdigit():
print("The string contains only digits!")
else:
print("The string does not contain only digits.")
輸出
The string contains only digits!
現在讓我們看看一個字串也包含非數字字元的例子。
示例
在這個例子中,字串 my_string 包含非數字字元(“a” 和“b”)。當我們執行程式碼時,輸出將為“字串不只包含數字”,因為 isdigit() 方法返回 False。
my_string = "12ab"
if my_string.isdigit():
print("The string contains only digits!")
else:
print("The string does not contain only digits.")
輸出
The string does not contain only digits.
示例
在這個例子中,我們首先提示使用者使用 input() 函式輸入一個字串。然後我們使用 isdigit() 方法檢查字串是否只包含數字。如果字串只包含數字,則列印“字串只包含數字”。否則,列印“字串不只包含數字”。
input_str = input("Enter a string: ")
if input_str.isdigit():
print("The string contains only digits.")
else:
print("The string does not contain only digits.")
輸出
Enter a string: 357sfy The string does not contain only digits.
示例
在這個例子中,我們定義了一個名為 contains_only_digits() 的函式,該函式以字串作為輸入,並使用 for 迴圈和 isdigit() 方法檢查它是否只包含數字。如果字串只包含數字,則函式返回 True。否則,返回 False。
然後我們定義一個名為 my_string 的字串,它只包含數字,並使用 my_string 作為輸入呼叫 contains_only_digits() 函式。由於 my_string 只包含數字,因此輸出將為“字串只包含數字!”。
def contains_only_digits(input_str):
for char in input_str:
if not char.isdigit():
return False
return True
my_string = "1234"
if contains_only_digits(my_string):
print("The string contains only digits!")
else:
print("The string does not contain only digits.")
輸出
The string contains only digits!
示例
在這個例子中,我們使用 re 模組來檢查字串是否只包含數字。我們定義一個名為 my_string 的字串,它包含非數字字元(“a” 和“b”)。然後我們使用 re.fullmatch() 函式來檢查 my_string 是否只包含數字。
正則表示式模式 r"\d+" 匹配一個或多個數字。如果 my_string 匹配此模式,則它只包含數字,輸出將為“字串只包含數字!”。否則,輸出將為“字串不只包含數字”。
import re
my_string = "12ab"
if re.fullmatch(r"\d+", my_string):
print("The string contains only digits!")
else:
print("The string does not contain only digits.")
輸出
The string does not contain only digits.
示例
在這個例子中,我們使用 re 模組來檢查字串是否只包含數字。我們定義一個名為 my_string 的字串,它包含所有數字字元(123456)。然後我們使用 re.search() 函式來檢查 my_string 是否只包含數字。
正則表示式模式 r"\d+" 匹配一個或多個數字。如果 my_string 匹配此模式,則它只包含數字,輸出將為“字串只包含數字!”。否則,輸出將為“字串不只包含數字”。
import re
my_string = "123456."
if re.search("\d+", my_string):
print("The string contains only digits.")
else:
print("The string does not contain only digits.")
輸出
The string contains only digits.
示例
在這個例子中,我們使用 re 模組來檢查字串是否只包含數字。我們定義一個名為 my_string 的字串,它包含非數字字元(“c”,“d”)。然後我們使用 re.findall() 函式來檢查 my_string 是否只包含數字。
正則表示式模式 r"\d+" 匹配一個或多個數字。如果 my_string 匹配此模式,則它只包含數字,輸出將為“字串只包含數字!”。否則,輸出將為“字串不只包含數字”。
import re
my_string = "5678cd."
if re.findall("r\d+", my_string):
print("The string contains only digits.")
else:
print("The string does not contain only digits.")
輸出
The string does not contain only digits.
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP