【问题标题】:Finding values in a string using for loops in Python 3在 Python 3 中使用 for 循环查找字符串中的值
【发布时间】:2017-01-29 18:34:57
【问题描述】:

我正在编写一个代码,提示用户输入一个定义为 str1 的句子,然后提示输入定义为 str2 的单词。

例如:

    Please enter a sentence: i like to code in python and code things
    Thank you, you entered:  i like to code in python and code things
    Please enter a word: code

我想使用 for 循环在 str1 中查找 str2,并打印该单词是否已找到,如果已找到,则打印 str2 的索引位置。

目前我有这个代码:

    str1Input = input("Please enter a sentence: ")
    print("Thank you, you entered: ",str1Input)

    str1 = str1Input.split()

    str2 = input("Please enter a word: ")

    for eachWord in str1:
        if str2 in str1:
            print("That word was found at index position", str1.index(str2)+1)
        else:
            print("Sorry that word was not found")

虽然结果似乎打印了是否在 str1 中为句子中的每个单词找到了单词的索引值一次?例如,如果 str1 是“apples oranges lemons limes pears”,我选择了“apples”这个词,它会想出:

    That word was found at index position: 1
    That word was found at index position: 1
    That word was found at index position: 1
    That word was found at index position: 1
    That word was found at index position: 1

如果有人可以帮助我和尝试类似的事情的其他人,那将非常有帮助!谢谢! :)

【问题讨论】:

  • 只是在给定字符串中找到搜索词的位置吗?
  • 是的,这是正确的,如果给定字符串中有 2 个或多个相同的单词,我希望它能够打印它们的索引位置
  • 如果你用空格分割,那么如何在列表中的一个元素中重复一个单词?除非您有像 cancan 这样的词并且正在搜索词 can。您还使用循环for eachWord in str1:,然后永远不要使用eachWord!您在每次迭代中都进行相同的搜索。

标签: python string python-3.x for-loop


【解决方案1】:

你的代码的问题是你使用for eachWord in str1。这意味着您遍历str1 中的每个字符,而不是每个单词。要解决此问题,请使用str1.split() 分隔单词。您还应该在 for 循环之外有 if str2 in str2 ;检查str2是否在str1中,如果是则遍历str1,而不是遍历str1,每次都检查是否包含str2。一次,您将无法使用str1.split().index() 查找所有位置,因为index() 总是返回列表中项目的最低位置。

更简单的方法是使用list comprehension

positions=[x for x in range(len(str1.split()))if str1.split()[x]==str2]

这将包含str1.split()str2 的所有索引。

最终代码:

positions=[x for x in range(len(str1.split()))if str1.split()[x]==str2]
if positions:
    for position in positions:
        print("That word was found at index position",position)
else:
    print("Sorry that word was not found")

输入:

Please enter a sentence: i like to code in python and code things
Thank you, you entered:  i like to code in python and code things
Please enter a word: code

输出:

That word was found at index position 3
That word was found at index position 7

【讨论】:

  • 感谢您的回复,我已经使用我的 for 循环方法编辑了代码,并设法找到了一种方法来打印单词的索引位置,尽管它为索引位置的数量打印了相同的消息对于句子中索引位置的总数,而不是重复它(甚至没有索引位置)。这是向前迈出的一步。有没有一种方法最好使用 for 循环方法,我可以让它打印出索引位置一次,如果它在句子中出现多次,还打印单词的索引位置?我的新代码在问题框中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2015-09-22
相关资源
最近更新 更多