Python String isalpha() 方法是用於字符串處理的 內置 方法。如果字符串中的所有字符都是字母,則 isalpha() 方法返回 “True”,否則返回 “False”。此函數用於檢查參數是否僅包含字母字符(如下所述)。
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
用法:
string.isalpha()
參數:
isalpha() 不帶任何參數
返回值:
- True:如果字符串中的所有字符都是字母表。
- False:如果字符串包含 1 個或多個非字母。
Errors and Exceptions:
- 它不包含參數,因此如果傳遞參數會發生錯誤
- 大寫和小寫字母都返回 “True”
- 空格不被認為是字母表,因此它返回 “False”
例子
Input:string = 'Ayush' Output:True Input:string = 'Ayush Saxena' Output:False Input:string = 'Ayush0212' Output:False
例 1:isalpha() 的工作
Python3
# Python code for implementation of isalpha()
# checking for alphabets
string = 'Ayush'
print(string.isalpha())
string = 'Ayush0212'
print(string.isalpha())
# checking if space is an alphabet
string = 'Ayush Saxena'
print( string.isalpha())
輸出:
True False False
例二:實際應用
給定 python 中的字符串,計算字符串中的字母數並打印字母。
Input:string = 'Ayush Saxena' Output:11 AyushSaxena Input:string = 'Ayush0212' Output:5 Ayush
算法:
- 將新字符串和變量 counter 初始化為 0。
- 逐個字符遍曆給定的字符串直到其長度,檢查字符是否為字母表。
- 如果是字母表,將計數器加 1 並將其添加到新字符串中,否則遍曆到下一個字符。
- 打印計數器的值和新字符串。
Python3
# Python program to illustrate
# counting number of alphabets
# using isalpha()
# Given string
string='Ayush Saxena'
count=0
# Initialising new strings
newstring1 =""
newstring2 =""
# Iterating the string and checking for alphabets
# Incrementing the counter if an alphabet is found
# Finally printing the count
for a in string:
if (a.isalpha()) == True:
count+=1
newstring1+=a
print(count)
print(newstring1)
# Given string
string='Ayush0212'
count=0
for a in string:
if (a.isalpha()) == True:
count+=1
newstring2+=a
print(count)
print(newstring2)
輸出:
11 AyushSaxena 5 Ayush
相關用法
- Numpy string isalpha()用法及代碼示例
- Python Pandas Series.str.isalpha()用法及代碼示例
- Python String casefold()用法及代碼示例
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 Python String isalpha() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。