檢查Python字串是否只包含字母的方法


Python被世界各地的程式設計師用於不同的目的,例如Web開發、資料科學、機器學習以及執行各種不同的自動化流程。在本文中,我們將學習檢查給定的Python字串是否只包含字元的不同方法。

檢查給定字串是否只包含字母的不同方法

isalpha函式

這是檢查給定的Python字串是否包含字母的最簡單方法。根據字串中字母的存在,它將輸出true或false。讓我們透過一個例子來更好地理解它。

示例

def letters_in_string(string): # A new function is created giving the string as input and the function isalpha is run in it to check the presence of letters 
    return string.isalpha() 

# Example 
main_string = "Hi! I am John." # The string is given as input
check = letters_in_string(main_string) # The function letter_in_string is run
print(check)  # The output will be displayed as true or false

輸出

上面示例的輸出如下所示

False 

正則表示式

正則表示式模組用於處理Python程式中存在的正則表示式。這是一種非常簡單的方法,可以檢查字串是否只包含字母。讓我們透過一個例子來更好地理解它。

示例

import re # Do not forget to import re or else error might occur

def letters_in_string(string): # The function is given with input of string
    pattern = r'^[a-zA-Z]+$'  # All the different alphabetic characters will be detected
    return re.match(pattern, string) is not None # The match function of the regular expression module will be given the string as input and it will check if only letters are present in the string

# Example 
main_string = "MynameisJohn" # The string is given as input
check = letters_in_string(main_string) # The string is given as input
print(check)

輸出

上面示例的輸出如下所示

True 

ASCII值

這是一種複雜的方法,但它是查詢字串是否只包含字母的非常有效的方法。在ASCII中,不同的字元對應不同的程式碼。因此,在這種方法中,我們將檢查字串是否包含定義範圍內的字元。讓我們透過一個例子來更好地理解它。

示例

def letters_in_string(string): # A function is defined with the string as input
    for char in string:
        ascii_val = ord(char) # The ASCII value will be found for different characters in the input
        if not (65 <= ascii_val <= 90 or 97 <= ascii_val <= 122): # A range is defined and if the characters will be within defined range then the output will be as true and if the characters are not within the range it will be displayed as output
            return False
    return True

# Example 
main_string = "MynameisJohn"
check = letters_in_string(main_string)
print(check)

輸出

上述程式碼的輸出如下所示

True

對於Unicode字元

這是一個非常特殊的情況,如果字串輸入的是Unicode字元,則可能顯示錯誤的輸出。因此,在這種情況下,我們將使用帶有Unicode字元的正則表示式模組。讓我們透過一個例子來更好地理解它。

示例

import unicodedata # Do not forget import unicodedata or else error might occur

def letters_in_strings(string): # A new function is run with string as the input
    for char in string:
        if not unicodedata.category(char).startswith('L'):
            return False
    return True

# Example 
input_string = "こんにちは"
result = letters_in_strings(input_string)
print(result) 

輸出

上面示例的輸出如下所示

True 

結論

有很多方法可以確定Python中給定的字串是否只包含字母。最佳方法取決於您的特定需求。本文介紹了四種方法:isalpha() 函式、帶有ASCII值的正則表示式、帶有Unicode字元特徵的正則表示式以及遍歷字串中的字元。使用這些方法,您可以快速確定您的Python程式中的字串是否只包含字母。

更新於:2023年8月1日

208 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告