Python字符串 isalpha() 方法是用于字符串处理的内置方法。如果字符串中的所有字符都是字母,则isalpha()方法返回“True”,否则返回“False”。此函数用于检查参数是否仅包含字母字符(如下所述)。
null
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvxyz
语法:
一串isalpha()
参数:
isalpha()不接受任何参数
返回:
- 符合事实的 :如果字符串中的所有字符都是字母。
- 错误的 :如果字符串包含一个或多个非字母。
错误和例外:
- 它不包含参数,因此如果传递了参数,则会发生错误
- 大写和小写字母都返回“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
例2:实际应用
给定python中的一个字符串,计算字符串中的字母数并打印字母。
Input : string = 'Ayush Saxena' Output : 11 AyushSaxena Input : string = 'Ayush0212' Output : 5 Ayush
算法:
- 将新字符串和变量计数器初始化为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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END