首頁  >  文章  >  後端開發  >  如何使用 Python 提取括號內的文字?

如何使用 Python 提取括號內的文字?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 12:37:02937瀏覽

How do you extract text within parentheses using Python?

Extracting Text Within Parentheses Using Python

To extract the contents within a pair of parentheses from a string, you can utilize Python's string slicing and the find() method.

Consider the following string:

u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

To obtain the text within the parentheses, you can apply the following steps:

  1. Locate the position of the opening parenthesis using the find() method.
  2. Eliminate this parenthesis from the string with slicing.
  3. Locate the position of the closing parenthesis using find() again.
  4. Utilize slicing to retrieve the desired text.

This process can be expressed in Python code as follows:

parenthetical_text = s[s.find("(")+1:s.find(")")]

Using this approach, the result will be:

date=\'2/xc2/xb2\',time=\'/case/test.png\'

以上是如何使用 Python 提取括號內的文字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn