Python String isalpha()方法示例

Python Python中的String isalpha()方法用于检查给定的字符串是否仅包含字母。换句话说,可以说这是一种处理字符串的方法。如果字符串的每个字符都是字母,Python isalpha()返回True,否则返回False。

Python字符串isalpha()

内容概述

  • 1个Python字符串isalpha()
  • 2错误和异常
  • 3相关文章

如果要检查字符串是否仅包含字母,那么Python isalpha()函数可以解决您的问题。请参见以下语法。

句法

string.isalpha()

它不需要任何参数。如果我们尝试将任何参数传递给方法,将显示错误。

如果字符串仅包含字母,则isalpha()函数将返回true。 (大写和小写)

如果字符串不包含字母或包含非字母的数字(例如数字或特殊字符),则Python字符串isalpha()函数将返回False。当它标识一个空格时,它也返回False。

算法

1.将新的字符串和变量计数器初始化为0。
2.遍历给定的字符串字符直至其长度,检查该字符是否为字母。
3.如果是字母,则将计数器加1并将其添加到新字符串中,否则遍历下一个字符。
4.打印计数器的值和新字符串。

isalpha()方法的示例程序

编写程序以显示isalpha()的机制

# app.py

string = "HelloBoy"
string2 = "Hello Boy"
print("This string will return true as it contains only alphabets:")
print("String=", string)
print(string.isalpha())
print("This string will return false as it contains alphabets and one space:")
print("String=", string2)
print(string2.isalpha())

输出量

➜  pyt python3 app.py
This string will return true as it contains only alphabets:
String= HelloBoy
True
This string will return false as it contains alphabets and one space:
String= Hello Boy
False
➜  pyt

编写一个程序来计算字符串的字母。

# app.py

string = "Hello World"
count = 0
count1 = 0
for i in string:
    if(i.isalpha()) == True:
        count = count+1
for i in string:
    count1 = count1+1
print("String: ", string)
print("Length of the string including space: ", count1)
print("Length of the string just by counting alphabets: ", count)

输出量

➜  pyt clear
➜  pyt python3 app.py
String:  Hello World
Length of the string including space:  11
Length of the string just by counting alphabets:  10
➜  pyt

错误和异常

  1. 它不包含任何参数。因此,如果传递参数,则会发生错误。
  2. 大写和小写字母都返回“ True”。
  3. 空格不是字母。因此,它返回“ False”。

最后,Python String isalpha()方法示例结束。

相关文章

Python字符串isalnum()

python字符串encode()

Python字符串isdecimal()

Python字符串isdigit()

列出的Python字符串

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Ankit Lathiya所有,未经许可,不得转载
你可能还喜欢