为什么这个字符串处理不起作用?

2024-09-19 23:32:17 发布

您现在位置:Python中文网/ 问答频道 /正文

inp = input("Enter word")
inplen = len(inp)

text = "sandwich"
textlen = len(text)

if inplen >= textlen:
    if inp[0] == text[0]:
        print("s")
if inplen >= textlen:
    if inp[1] == text[1]:
        print("a")
if inplen >= textlen:
    if inp[2] == text[2]:
        print("n")
if inplen >= textlen:
    if inp[3] == text[3]:
        print("d")
if inplen >= textlen:        
    if inp[4] == text[4]:
        print("w")
if inplen >= textlen:        
    if inp[5] == text[5]:
        print("i")
if inplen >= textlen:        
    if inp[6] == text[6]:
        print("c")
if inplen >= textlen:
    if inp[7] == text[7]:
        print("h")

当我没有输入完整的“三明治”时,我不会得到输出。我想做的是,程序应该打印所有正确的字母,已经输入匹配“sandhich”。因此,当输入“sandwooh”时,程序应该返回“s”“a”“n”“d”“w”“h”,当输入“sand”时,程序应该返回“s”“a”“n”“d”。 谢谢


Tags: text程序inputlenif字母wordprint
2条回答

您只需按以下步骤进行:

in_text = str(input("Enter word: "))
print(list(set(input) & set('sandwich')))

set(a) & set(b)返回一个集合,其中包含ab共有的元素list()然后将它们转换为一个列表,然后打印它们。举个例子:

>>> print(list(set('sandstorm') & set('sandwich')))
['s', 'a', 'n', 'd']

在这里,循环要容易得多:

text = "sandwich"
inp = input("Enter word")

# a range from zero to the length of the shortest string
# (if one string is longer than the other, we want the length of the shortest
#  one so that it doesn't try to check characters that don't exist)
for i in range(min(len(text), len(inp))):
    # print if corresponding characters match
    if inp[i] == text[i]:
        print(text[i])

相关问题 更多 >