【问题标题】:String indexing字符串索引
【发布时间】:2017-01-27 16:41:00
【问题描述】:

Python 3.5

这是我的代码:

str1 = input("Please enter a full sentence: ").lower()
print("Thank you, You entered:" , str1)

str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower()

if str2 in str1:
    print("That word was found!")
else:
    print("Sorry, that word was not found")

按原样,它将搜索输入的单词(str2),如果在输入(str1(一个句子))中找到它,它会说“该单词已找到”)。如果该单词不在句子中,它将显示“未找到该单词”。

我想开发这个,所以当搜索并找到单词时,它会告诉用户单词 (str2) 在句子 (str1) 中的索引位置。例如:如果我有句子(“I like to code in Python”)并且我搜索单词(“code”),程序应该说“该单词在索引位置找到:4”。

顺便说一句,代码不区分大小写,因为它使用 .lower 将所有单词转换为小写。

如果有人可以给我一些建议,那将非常感激!

【问题讨论】:

  • 您使用的是 Python 2.7 还是 Python 3?

标签: string indexing python-3.5


【解决方案1】:
print("That word was found at index %i!"% (str1.split().index(str2)))

这将打印 str1 中第一次出现 str2 的索引。
完整代码为:

str1 = input("Please enter a full sentence: ").lower()
print("Thank you, You entered:" , str1)

str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower()

if str2 in str1:
    print("That word was found!")
    print("that word was found in index position: %i!"% (str1.split().index(str2)))

, str1.index(str2))
别的: print("对不起,找不到那个词")

【讨论】:

  • 不完全是。 str1.split().index(str2)
  • 是的,语法无效
  • 嗯....我没有收到语法错误....您输入的输入是否用引号括起来?
  • 对不起@LukeP_8,我的回答假设您使用的是 Python 2.7!您可能希望将其添加为标签。
  • 您还有其他类似的答案可以在 Python 3.5 中使用吗?
【解决方案2】:

您可以使用 split() 方法:它在字符串值上调用并返回字符串列表。然后使用 index() 方法查找字符串的索引。

str1 = input("Please enter a full sentence: ").lower()
print("Thank you, You entered:" , str1)
str2 = input("Now please enter a word included in your sentence in anyway you like: ").lower()

if str2 in str1:
    a = str1.split() # you create a list
    # printing the word and index a.index(str2)
    print('The ', str2,' was find a the index ', a.index(str2)) 
    print("That word was found!")
else:
    print("Sorry, that word was not found")

【讨论】:

    【解决方案3】:

    你可以用这个替换你的if ... else

    try:
        print("That word was found at index %i!"% (str1.split().index(str2) + 1))
    except ValueError:
        print("Sorry, that word was not found")
    

    【讨论】:

    • 谢谢,这对我有用。很好很简单,对原始代码几乎没有改动,这是我想要的那种东西。干杯! :)
    【解决方案4】:
    str2 = 'abcdefghijklmnopqrstuvwxyz'
    str1 = 'z'
    index = str2.find(str1)
    if index != -1:
        print 'That word was found in index position:',index
    else:
        print 'That word was not found'
    

    这将打印str2中str1的索引

    【讨论】:

    • 我不会命名变量str,你可以from string import ascii_lowercase 来获取字母表
    • 你说得对,但他显然是 python 新手,我不想将他与那个导入混淆。
    • 谢谢,这对我有用。但由于某种原因,它没有给我正确的索引号。例如,如果我为 str1 提供“我喜欢用 Python 编写代码”,然后搜索“代码”,它会告诉我它在索引位置 10 中吗?有没有办法解决这个问题?
    • 其实没错。从 0 开始计数,单词“code”从索引 10 开始。
    猜你喜欢
    • 2010-10-27
    • 2014-11-06
    • 2015-11-17
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    相关资源
    最近更新 更多