如何让我的 python 程序获得字符串的索引?
How do I make my python program get the index of a string?
我想让我的 python 2.7 程序获取字符串中特定字符的索引。所以像这样:
获取任意字符串中[和]括号的索引。例如:
"Hello World [These brackets] Hello World"
程序应该 return 12 和 27。有什么方法可以让我的 python 程序做到这一点吗?如果没有,那我倒霉了。
python中的indexof
函数是index:
>>> "Hello World [These brackets] Hello World".index('[')
12
>>> "Hello World [These brackets] Hello World".index(']')
27
索引呢?
text = "Hello World [These brackets] Hello World"
idx1 = text.index("[")?
idx2 = text.index("]")?
警告,这 returns 只是第一场比赛。
一种您可以看到但我仍然更喜欢使用 indexof 函数的简单方法:
>>> a = "Hello World [These brackets] Hello World"
>>> for i in xrange(len(a)):
... if a[i] == '[' or a[i] == ']':
... print i
...
12
27
我想让我的 python 2.7 程序获取字符串中特定字符的索引。所以像这样:
获取任意字符串中[和]括号的索引。例如:
"Hello World [These brackets] Hello World"
程序应该 return 12 和 27。有什么方法可以让我的 python 程序做到这一点吗?如果没有,那我倒霉了。
python中的indexof
函数是index:
>>> "Hello World [These brackets] Hello World".index('[')
12
>>> "Hello World [These brackets] Hello World".index(']')
27
索引呢?
text = "Hello World [These brackets] Hello World"
idx1 = text.index("[")?
idx2 = text.index("]")?
警告,这 returns 只是第一场比赛。
一种您可以看到但我仍然更喜欢使用 indexof 函数的简单方法:
>>> a = "Hello World [These brackets] Hello World"
>>> for i in xrange(len(a)):
... if a[i] == '[' or a[i] == ']':
... print i
...
12
27