查找列表中第一次出现的字符

问题描述

我想要一个代码,输入行数(计算空行),然后是行本身,然后是我想要查找的单词,最后是一个字符第一次出现的位置。请不要import

我有这个:

lines = int(input())
phrases = []

for i in range(lines):
  phrase = str(input())
  phrase = phrase.replace(',','')
  phrase = phrase.replace('!','')
  phrase = phrase.replace('.','')
  phrase = phrase.replace(';','')
  phrase = phrase.replace(':','')
  phrase = phrase.replace('?','')
  phrase = phrase.replace(' ','')
  phrase = phrase.lower()
  phrases.append(phrase)

word = str(input())

所以输入将是这样的:

6  
I have a computer  

Hello world    
Please help  
dammit code  
I wish I finished this today  
happy   

我希望结果如下:

Word founded  
h: word 2,letter 1  
a: word 3,letter 1  
p: word 4,letter 4
p: word 7,letter 1  
y: word 16,letter 5

不能和上一个一个词。
如果没有发生这种情况,请打印:

Word not founded

解决方法

可能是这样的:

lines = int(input())
words = []

for i in range(lines):
    phrase = input().lower()
    if phrase:
        words.extend(phrase.split(' '))

search_word = input()
output_rows = []
word_found = True

for i,word in enumerate(words):
    if search_word[0] in word:
        output_rows.append(f'{search_word[0]}: word {i+1},letter {word.index(search_word[0])+1}')
        search_word = search_word[1:]
        if not search_word:
            break
else:
    print("Word not found")
    word_found = False

if word_found:
    print("Word found")
    print('\n'.join(output_rows))
,

您可以尝试使用 list.extend() 方法:

import re

lines = int(input("How many lines? >>> "))
words = []

for _ in range(lines):
    text = input(">>> ").lower()
    words.extend(re.findall(r'\b\S+\b',text))

word = input("Input word >>> ")
i = 0
output = []
for index,w in enumerate(words):
    for letter in word[i:]:
        if letter in w:
            output.append(f"{letter}: w {index + 1},l {w.index(letter) + 1}")
            i += 1
            break
    else:
        print("Word not founded.")
        break
else:
    print("Word founded.")
    print("\n.join(output)")