Skip to main content
 首页 » 编程设计

python之如何检查单词是否以字母表范围内开头

2025年05月04日12cyq1162

我有这个简单的程序

quote = input("Enter your name : ") 
start=0 
space_index=quote.find(" ") 
while space_index != -1: 
   print(quote[start:space_index])  

我希望出现的任何单词都应以a 到g 开头。 我尝试了导入字符串类并使用他的 ascii_lowercase() 函数,但我仍然无法弄清楚如何检查单词是否以 a 到 g 范围开头。

请您参考如下方法:

只需使用 startswith()像这样:

quote = input("Enter your name : ") 
allowed = 'abcdefg' 
if any(quote.startswith(x) for x in allowed): 
   print('Success!')  

或者,为了使它更灵活,你可以使用这个:

import string 
start = 'a' 
end = 'g' 
letters = string.ascii_lowercase 
allowed = letters[letters.index(start):letters.index(end)+1]  # abcdefg 
quote = input("Enter your name : ") 
 
while not any(quote.startswith(x) for x in allowed): 
    quote = input("The name is not valid! Please enter another name: ") 
print('Success!')