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

Finding the first occurrence of a character in a list

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

我有这个 rn:

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)")