Python 查找列表中字符的第一个匹配项
我需要一个代码,输入行数(计算空行数),然后输入行本身,然后输入我要查找的单词,最后输入一个字符第一次出现的位置。请不要输入Python 查找列表中字符的第一个匹配项,python,list,word,find-occurrences,Python,List,Word,Find Occurrences,我需要一个代码,输入行数(计算空行数),然后输入行本身,然后输入我要查找的单词,最后输入一个字符第一次出现的位置。请不要输入imports 我有一个问题: lines = int(input()) phrases = [] for i in range(lines): phrase = str(input()) phrase = phrase.replace(',','') phrase = phrase.replace('!','') phrase = phrase.repl
import
s
我有一个问题:
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)")
你的问题是什么?请拿着这本书,读着,还有那本。您应该考虑您的问题以包括实际输出,以及您的代码如何无法满足您的期望。欢迎来到堆栈溢出!空的是计数还是不计数?是的,它们是计数的,我放了5行,但它是6行,很抱歉你没有在这段代码中调用
get\u index\u position
。请编辑你的问题并提供一个runnable。唯一缺少的一点是显示“Word not founded”的那一行。@ra10121416这到底是什么意思?谢谢比如,如果不是所有的字符都成立,那么它应该打印“Word not founded”。例如:2‘hello world’‘bye world’‘halo’它包含“h”,但不包含“a”,所以它应该打印为“Word not founded”。@ra10121416将其改为打印“Word found”和“Word not found”,非常感谢!!唯一缺少的是,当你找到单词的所有字母时,它不会打印“Word founded”,正如我在问题中提到的。当不是所有的角色都成立时,“单词未成立”。例如:2‘hello world’‘bye world’‘halo’它包含“h”,但不包含“a”,所以应该打印为“Word not founded”@ra10121416我明白了。更新:)