📜  Python String isalpha() 方法

📅  最后修改于: 2022-05-13 01:55:50.032000             🧑  作者: Mango

Python String isalpha() 方法

Python String 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())


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)


输出:

True
False
False

示例 2:实际应用

给定Python中的字符串,计算字符串中字母的数量并打印字母。

Input : string = 'Ayush Saxena'
Output : 11
         AyushSaxena

Input : string = 'Ayush0212'
Output : 5
         Ayush

算法:

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

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