Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Need help in understanding the below python string extraction

I read the below code about string extraction in python

text[text.find("insert"):(len(text),text.find("Configure"))[text.find("Configure")>1]]

and I am not able to understand this part

(len(text),text.find("Configure"))[text.find("Configure")>1]

How does this work? Can some one help me?

question from:https://stackoverflow.com/questions/66045375/need-help-in-understanding-the-below-python-string-extraction

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several pieces of code involved in this one line:

I am considering variable text is of str type

  1. (len(text),text.find("Configure")) This code will return a tuple of int, example: (100, 10)
  2. [text.find("Configure")>1] This code will return a list of bool either [True] or [False]
  3. Now combining both code blocks above, if index of "Configure" is greater than 1 then it will be True i.e. 1 so element in tuple at index 1 will be taken i.e. 10, else condition will be False i.e. 0 so element at index 0 will be taken i.e. 100 (from the example tuple defined above)
(len(text),text.find("Configure"))[text.find("Configure")>1]
  1. The whole line boils down to:
text[text.find("insert"):100]

or

text[text.find("insert"):10]

and this is basic string slicing in Python


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...