Python程序在给定字符串中查找匹配的字符

这篇文章展示了如何使用Python的if语句和正则表达式来检查用户输入的字符串中是否存在特定字符。如果所有匹配字符都找到,程序将输出'Completely In',否则输出'Not In'和匹配的数量。
摘要由CSDN通过智能技术生成

In this article, we are going to implement some of the features of if statement to verify the characters present inside the entered string.

在本文中,我们将实现if语句的某些功能,以验证输入的string中存在的字符

User is asked to enter a string with many characters as per user's choice and the code will check whether the string has some of the listed characters inside in it. If the string has all characters matched with the listed one, then it prints "Completely In" and else "Not In" with the number of characters matched.

根据用户的选择,要求用户输入包含许多字符的字符串,然后代码将检查该字符串是否包含其中列出的某些字符 。 如果该字符串的所有字符都与列出的字符匹配,则它会打印“ Completely In” ,否则显示“ Not In”,并显示匹配的字符数。

So here is the code:

所以这是代码:

secretword = str(input("Enter a string: "))
lettersGuessed = ['a', 'e', 'i', 'k', 'p', 'r', 's','l']
flag = 0

for i in secretword:
        if i in lettersGuessed:
             flag+=1
if len(secretword) == flag:
    print("Completely In")
else:
    print("Not In")

print(flag, 'matches')    

Output:

输出:

First run:
Enter a string: aeiprsl
Completely In
7 matches

Second run:
Enter a string: xyz
Not In
0 matches


翻译自: https://www.includehelp.com/python/find-the-matched-characters-in-a-given-string.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值