简体   繁体   中英

How to find the index of a substring having two parts (with unknown number of white spaces) in a multi line string in Python

I have a multiple line string.

string="""
abc def ghi
jkl end vjk
mno pqr stu
"""

I want the index of the substring 'end vjk'. The index can be found as string.index('end vjk') . But the problem is that the second part of the substring is not known before hand (vjk can be replaced randomly by any other string). Also the white spaces between the two parts may vary.

I tried with the following code.

variable='vjk'
compare='end'(\s*) '%s' %variable
string.index(compare)

But the code in not working. Can any body suggest what I am doing wrong?

Do you want something like this?

variable='vjk'
compare='end %s' %variable
string.index(compare)

regex can be used to solve this issue.

string="""
abc def ghi
jkl end vjk
mno pqr stu
"""   
var = 'vjk'
s = re.search("end\s+{}".format(var),string)
string.index(s.group()) # -> 17 in this case

A Regex object's search() method searches the string it is passed for any matches to the regex. Match objects have a group() method that will return the actual matched text from the searched string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM