python中isalpha的用法_Python string isalpha()用法及代码示例

在Python中,isalpha()是用于字符串处理的内置方法。如果字符串中的所有字符都是字母,则isalpha()方法返回“True”,否则,返回“False”。此函数用于检查参数是否包含任何字母字符,例如:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

用法:

string.isalpha()

参数:

isalpha() does not take any parameters

返回:

1.True- If all characters in the string are alphabet.

2.False- If the string contains 1 or more non-alphabets.

例子:

Input:string = 'Ayush'

Output:True

Input:string = 'Ayush Saxena'

Output:False

Input:string = 'Ayush0212'

Output:False

# 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

错误和异常

它不包含任何参数,因此如果传递参数,则会发生错误

大写和小写字母都返回“True”

空格不被视为字母,因此它返回“False”

应用:给定python中的字符串,计算字符串中的字母数并打印字母。

例子:

Input:string = 'Ayush Saxena'

Output:11

AyushSaxena

Input:string = 'Ayush0212'

Output:5

Ayush

算法

1.将新的字符串和变量计数器初始化为0。

2.逐字符遍历给定的字符串字符直至其长度,检查字符是否为字母。

3.如果是字母,则将计数器增加1并将其添加到新字符串中,否则遍历下一个字符。

4.打印计数器的值和新字符串。

# 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


版权声明:本文为weixin_39878855原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。