【问题标题】:Find position of word/substring in string (python 3.4.3)在字符串中查找单词/子字符串的位置(python 3.4.3)
【发布时间】:2016-02-01 20:47:41
【问题描述】:

我想查找WHOLE字在字符串中的位置,但我的代码显示了字的第一个字符的位置。

string = input("Please input a sentence: ")
word = input("Please input a word: ")
string.lower()
word.lower()
list1 = string.split(' ')
position = string.index(word)
print (position)

【问题讨论】:

  • 请澄清一下
  • 指定你使用的语言,然后我会确定这个重复的问题:-)
  • 我是编码初学者,所以如果不正确,我很抱歉,但如果你所说的语言是程序,我使用的是 Python 3.4.3 Shell
  • 你解决了吗?
  • 是的 :-) 我将 string.index(word) 更改为 list1.index(word)

标签: python string python-3.x position substring


【解决方案1】:

由于您将单词作为输入询问,因此您知道单词大小并且知道起始索引,您可以这样做:起始索引 + 大小。

string = input("Please input a sentence: ")
word = input("Please input a word: ")
string.lower()
word.lower()
list1 = string.split(' ')
position = string.index(word)
print (position) // starting position
print (position + len(word) ) // end position

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多