Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.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
Python2.7搜索字符串_Python - Fatal编程技术网

Python2.7搜索字符串

Python2.7搜索字符串,python,Python,我需要打印“r”中的“word001%20”和“word002%20”。在“word001”和“word002”之后是随机数量的字符串(下面只是一个示例)。我尝试使用: r = "word001%20#something=637448word002%20#something=278364" a = str(r[r.index('word001'):r.index('#something')]) b = str(r[r.index('word002'):r.index('#something')]

我需要打印“r”中的“word001%20”和“word002%20”。在“word001”和“word002”之后是随机数量的字符串(下面只是一个示例)。我尝试使用:

r = "word001%20#something=637448word002%20#something=278364"
a = str(r[r.index('word001'):r.index('#something')])
b = str(r[r.index('word002'):r.index('#something')])
print a
print b

但只有“打印a”才有效。有什么想法吗?

这是因为,这里
b=str(r[r.index('word002'):r.index('something'))
r.index('something')
返回第一次出现的
\something
的索引

r[27:10] >>> ''
您可以使用
find
…在
word002

str(r[r.index('word002'):r.find('#something', r.index('word002'))])
'word002%20'
第二个
r.index('something')
将找到第一个。你需要像这样的东西:

a = str(r[r.index('word001'):r.index('#something')])
b = str(r[r.index('word002'):r.index('#something', start=r.index('#something')+1)])
这将找到第一个
#某物
,然后继续搜索

但是如果你需要找到更多的
word
模式,那就不是很好了。也许最好是:

import re
re.findall("(word\\d+%20)", "word001%20#something=637448word002%20#something=278364")  # this returns word0001%20 and word002%20

使用此字符串拆分和
索引可能会起作用,但使用正则表达式是更好的解决方案。这一款适合您的需要:

>>> import re
>>> r = "word001%20#something=637448word002%20#something=278364"
>>> print re.findall('(word001.*?)#something',r)
['word001%20']
>>> print re.findall('(word002.*?)#something',r)
['word002%20']

此正则表达式找不到要查找的字符串。它被要求提供一个匹配项,给出
word001%20