Home >Backend Development >C++ >How to Extract Text Enclosed in Parentheses in Python?

How to Extract Text Enclosed in Parentheses in Python?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-18 03:01:10249browse

How to Extract Text Enclosed in Parentheses in Python?

Extract text from brackets

In some cases, you may need to extract specific text contained within brackets. For example, consider the text "Username (Sales)" and the need to retrieve only the content within the brackets.

A straightforward way to do this without using regular expressions is to use string manipulation functions. Here’s how to do it:

<code class="language-python">input_string = "用户名 (销售)"
output = input_string.split('(', 1)[1].split(')', 1)[0]</code>

In this code, the split('(', 1) method splits the input string into two parts based on the specified delimiter (left bracket) and returns only the first two parts. Then, split(')', 1)[0] extracts the text inside the brackets from the second part (the content inside the brackets) and discards the closing bracket. This method works well when the opening and closing brackets are known and only appear once in the string.

Other methods may involve using regular expressions or iterating over string characters, but these are not explored here. The provided method provides a concise and efficient way to extract the text between brackets.

The above is the detailed content of How to Extract Text Enclosed in Parentheses in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn