Home >Backend Development >Python Tutorial >How to Extract Text Between Parentheses in Python?
Problem:
Given a string containing text enclosed in parentheses, extract the contents inside the parentheses. For example, in the string:
u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
the desired output is:
date=\'2/xc2/xb2\',time=\'/case/test.png\'
Solution Using Regular Expressions:
While regular expressions can be used to solve this problem, they are not the most straightforward solution.
A simpler approach is to use string manipulation:
s = "u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')" parentheses_content = s[s.find("(")+1:s.find(")")] print(parentheses_content)
This solution involves finding the positions of the opening and closing parentheses using the find() method, and then using string slicing to extract the contents.
The above is the detailed content of How to Extract Text Between Parentheses in Python?. For more information, please follow other related articles on the PHP Chinese website!