📌  相关文章
📜  Python|检查给定字符串是否仅包含字母的方法

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

Python|检查给定字符串是否仅包含字母的方法

给定一个字符串,编写一个Python程序来判断一个字符串是否只包含字母而没有其他关键字。让我们讨论一些完成任务的方法。

方法 #1:使用 isalpha() 方法

Python3
# Python code to demonstrate
# to find whether string contains
# only letters
 
# Initialising string
ini_str = "ababababa"
 
# Printing initial string
print ("Initial String", ini_str)
 
# Code to check whether string contains only number
if ini_str.isalpha():
    print("String contains only letters")
else:
    print("String doesn't contains only letters")


Python3
# Python code to demonstrate
# to find whether string contains
# only letters
import re
 
# Initialising string
ini_str = "ababababa"
 
# Printing initial string
print ("Initial String", ini_str)
 
# Code to check whether string contains only number
pattern = re.compile("^[a-zA-Z]+$")
if pattern.match(ini_str):
    print ("Contains only letters")
else:
    print ("Doesn't contains only letters")



方法 #2:使用 re

Python3

# Python code to demonstrate
# to find whether string contains
# only letters
import re
 
# Initialising string
ini_str = "ababababa"
 
# Printing initial string
print ("Initial String", ini_str)
 
# Code to check whether string contains only number
pattern = re.compile("^[a-zA-Z]+$")
if pattern.match(ini_str):
    print ("Contains only letters")
else:
    print ("Doesn't contains only letters")