一覧

2017-09-20 18 views
1

に含まれる文字の位置を探しますか?一覧

はこれが何をしたいです:

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. 
+0

あなたはすべての変数 'expression'を持っていないのはなぜ? –

+0

@JeremyMcGibbon私は質問を編集しました – Wowotek

答えて

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 
4
operator = ["&", "/", "->", "<->", "X", "I"] 
expression = "p&q->rXq" 
print(operator.index("<->")) 

これは、出力が表示されます:私はこのような出力に何か必要ですか?

+0

私は質問を編集しました – Wowotek