查找列表中包含的字符位置

时间:2017-09-20 05:18:55

标签: python python-3.x

如果我有这个变量

operator = ["&", "/", "->", "<->", "X", "I"]
expression = "p&q->rXq"

如何在`运算符中返回"&""X"的位置?我需要这样的输出:

1:0, 3:2, 6:4
#1 for "&", 3 for "->", 6 for "X" inside expression variable.
#0 for "&", 2 for "->", 4 for "X" inside operator List.

2 个答案:

答案 0 :(得分:4)

operator = ["&", "/", "->", "<->", "X", "I"]
expression = "p&q->rXq"
print(operator.index("<->"))

这将显示输出:

  

3

这是你想要的吗?

答案 1 :(得分:1)

operator = ["&", "/", "->", "<->", "X", "I"]
expression = "p&q->rXq"

resultString = ''
for one_op in operator: # for each character in your list
    startingIndex = expression.find(one_op) # important: assuming it appears only once, find() takes the first occurrence and returns the index
    if startingIndex is not -1: # if find() does not find an occurence, it will return -1
        resultString += (str(startingIndex) + ':' + str(operator.index(one_op)) + ',') # only that exist is considered

print(resultString.rstrip(','))

输出:

1:0,3:2,6:4