Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使python程序获得字符串的索引?_Python_String_Python 2.7_Indexof - Fatal编程技术网

如何使python程序获得字符串的索引?

如何使python程序获得字符串的索引?,python,string,python-2.7,indexof,Python,String,Python 2.7,Indexof,我希望python 2.7程序能够获取字符串中特定字符的索引。所以像这样: 获取任意字符串中[和]括号的索引。例如: "Hello World [These brackets] Hello World" 程序应该返回12和27。有没有办法让我的python程序实现这一点?如果没有,那我就倒霉了。python中的indexof函数是: python中的indexof函数是: 指数呢 text = "Hello World [These brackets] Hello World" idx1 =

我希望python 2.7程序能够获取字符串中特定字符的索引。所以像这样:

获取任意字符串中[和]括号的索引。例如:

"Hello World [These brackets] Hello World"

程序应该返回12和27。有没有办法让我的python程序实现这一点?如果没有,那我就倒霉了。

python中的
indexof
函数是:


python中的
indexof
函数是:

指数呢

text = "Hello World [These brackets] Hello World"
idx1 = text.index("[")?
idx2 = text.index("]")?
警告,这只返回第一个匹配项。

索引如何

text = "Hello World [These brackets] Hello World"
idx1 = text.index("[")?
idx2 = text.index("]")?

警告,这只返回第一个匹配项。

一种简单的方法,您可以看到,但我还是更喜欢使用indexof函数:

>>> a = "Hello World [These brackets] Hello World"
>>> for i in xrange(len(a)):
...     if a[i] == '[' or a[i] == ']':
...             print i
... 
12
27

您可以看到一种简单的方法,但我还是更喜欢使用indexof函数:

>>> a = "Hello World [These brackets] Hello World"
>>> for i in xrange(len(a)):
...     if a[i] == '[' or a[i] == ']':
...             print i
... 
12
27

我可以将xrange更改为range吗?或者xrange的存在是有原因的吗?有时使用xrange优于range,但您仍然可以使用range,在这方面没有问题。试着阅读以下内容:我可以将xrange更改为range吗?或者xrange的存在是有原因的吗?有时使用xrange优于range,但您仍然可以使用range,在这方面没有问题。试着读一下: