Using apply form pandas you can create a function which adds the brackets. In this case the function is an lambda function using the f-string.

df['Column_A'] = df['Column_A'].apply(lambda x: f'({x})')

# Example:
l = ['Anna', 'Mark', 'Emy']
df = pd.DataFrame(l, columns=['Column_A'])

  Column_A
0     Anna
1     Mark
2      Emy

df['Column_A'] = df['Column_A'].apply(lambda x: f'({x})')

  Column_A
0   (Anna)
1   (Mark)
2    (Emy)

Answer from 3dSpatialUser on Stack Overflow
🌐
Manifoldapp
cuny.manifoldapp.org › read › how-to-code-in-python-3 › section › 07f9968a-8f75-4d3c-8573-2e9282745e9e
How To Use String Formatters | How To Code in Python 3 | Manifold @CUNY
In sammy_string we added 4 pairs of curly braces as placeholders for variable substitution. We then passed 4 values into the str.format() method, mixing string and integer data types. Each of these values are separated by a comma. When we leave curly braces empty without any parameters, Python will replace the values passed through the str.format() method in order.
🌐
AskPython
askpython.com › home › how to print brackets in python?
How to Print Brackets in Python? - AskPython
April 19, 2026 - String concatenation using + works for building bracket-enclosed representations from dynamic data. Square brackets denote lists and serve as the indexing operator in Python.
Discussions

python - How to add round brackets to strings in column - Stack Overflow
I have a data frame with strings in Column_A: row1:Anna, row2:Mark, row3:Emy I would like to get something like:row1(Anna). row2:(Mark), row3:(Emy) I have found some examples on how to remove the More on stackoverflow.com
🌐 stackoverflow.com
arrays - Insert square brackets around specific words within a text string in Python? - Stack Overflow
I have a text string, and have identified a set of words which I want to wrap with []. I have stored these words in an array, and have also stored the index position of their first and last charact... More on stackoverflow.com
🌐 stackoverflow.com
Adding brackets to a list and sort it
Hello, I have the following assignment: Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
January 17, 2023
regex - surrounding a pattern in python string with brackets - Stack Overflow
I wrote a code that looks for the pattern "-d" in strings and partition the string after finding the pattern to 3 partitions before "-d", after "-d" and "-d" itself then I check the block before "-d" until I find whitespace or "{" and stop and add brackets. my code looks like this: P.S. More on stackoverflow.com
🌐 stackoverflow.com
🌐
EnableGeek
enablegeek.com › home › print your (box,curly, parentheses) brackets in python
Print Your (Box,Curly, Parentheses) Brackets in Python - EnableGeek
March 21, 2024 - In Python, you can include curly braces (also known as braces or brackets) in a string by escaping them using a backslash (‘\‘). Though this is old method. You can write curly bracaes normally to print braces.
Top answer
1 of 3
2

If you sort your list of phrases (I've called it words) in reverse order, you can insert the [ and ] around each phrase in a loop. The reason you need to do it backwards is because the insertion will change the indexes of subsequent characters in the string:

for w in sorted(words, key=lambda x:-x[1]):
    text = text[:w[1]] + '[' + text[w[1]:w[2]] + ']' + text[w[2]:]
    
print(text)

Output:

The SARs were leaked to the [Buzzfeed] website and shared with [the International Consortium of Investigative Journalists] (ICIJ). [Panorama] led the research for the [BBC] as part of a global probe. The ICIJ led the reporting of [the Panama Papers] and Paradise Papers leaks - secret files detailing the offshore activities of the wealthy and the famous. [Fergus Shiel], from the consortium, said the FinCEN [Files] are an insight into what banks know about the vast flows of dirty money across the globe… [The] system that is meant to regulate the flows of tainted money is broken. The leaked SARs had been submitted to [the US Financial Crimes Enforcement Network], or FinCEN between 2000 and 2017 and cover transactions worth about $2 trillion. [FinCEN] said the leak could impact [US] national security, risk investigations, and threaten the safety of those who file the reports. But [last week] it announced proposals to overhaul its anti-money laundering programmes. The [UK] also unveiled plans to reform its register of company information to clamp down on fraud and money laundering.The investment scam that [HSBC] was warned about was called WCM777. It led to the death of investor [Reynaldo Pacheco], who was found under water on a wine estate in [Napa], [California], in [April 2014]. Police say he had been bludgeoned with rocks. He signed up to the scheme and was expected to recruit other investors. The promise was everyone would get rich. A woman [Mr Pacheco], [44], introduced lost about $3,000. That led to the killing by men hired to kidnap him. He literally was trying to… make people's lives better, and he himself was scammed, and conned, and he unfortunately paid for it with his life,said [Sgt Chris Pacheco] (no relation), one of the officers who investigated the killing. Reynaldo, he said, was murdered for being a victim in a Ponzi scheme.

Demo on ideone

2 of 3
0

The following should work: l is your original list and t is yout text:

l=[list(i) for i in l]
for i in range(len(l)):
    x1, x2=l[i][1], l[i][2]
    t=t[:x1]+ '[' + t[x1:x2] + ']' +t[x2:]
    for k in range(i+1, len(l)):
        l[k][1]+=2
        l[k][2]+=2

This gives the following Output:

"The SARs were leaked to the [Buzzfeed] website and shared with [the International Consortium of Investigative Journalists] (ICIJ). [Panorama] led the research for the [BBC] as part of a global probe. The ICIJ led the reporting of [the Panama Papers] and Paradise Papers leaks - secret files detailing the offshore activities of the wealthy and the famous. [Fergus Shiel], from the consortium, said the FinCEN [Files] are an insight into what banks know about the vast flows of dirty money across the globe… [The] system that is meant to regulate the flows of tainted money is broken. The leaked SARs had been submitted to [the US Financial Crimes Enforcement Network], or FinCEN between 2000 and 2017 and cover transactions worth about $2 trillion. [FinCEN] said the leak could impact [US] national security, risk investigations, and threaten the safety of those who file the reports. But [last week] it announced proposals to overhaul its anti-money laundering programmes. The [UK] also unveiled plans to reform its register of company information to clamp down on fraud and money laundering.The investment scam that [HSBC] was warned about was called WCM777. It led to the death of investor [Reynaldo Pacheco], who was found under water on a wine estate in [Napa], [California], in [April 2014]. Police say he had been bludgeoned with rocks. He signed up to the scheme and was expected to recruit other investors. The promise was everyone would get rich. A woman [Mr Pacheco], [44], introduced lost about $3,000. That led to the killing by men hired to kidnap him. He literally was trying to… make people's lives better, and he himself was scammed, and conned, and he unfortunately paid for it with his life,said [Sgt Chris Pacheco] (no relation), one of the officers who investigated the killing. Reynaldo, he said, was murdered for being a victim in a Ponzi scheme."
🌐
freeCodeCamp
forum.freecodecamp.org › python
Adding brackets to a list and sort it - Python - The freeCodeCamp Forum
January 17, 2023 - Hello, I have the following assignment: Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if ...
🌐
Processing
py.processing.org › reference › indexbrackets
[] (Index brackets) \ Language (API)
Python Mode for Processing extends the Processing Development Environment with the Python programming language.
Top answer
1 of 2
5
>>> import re
>>> oldString = "this is my {{string-d}}"
>>> oldString2 = "this is my second{{ new_string-d }}"
>>> re.sub(r"(\w*-d)", r"(\1)", oldString)
'this is my {{(string-d)}}'
>>> re.sub(r"(\w*-d)", r"(\1)", oldString2)
'this is my second{{ (new_string-d) }}'

Note that this matches "words" assuming that a word is composed of only letters, numbers, and underscores.


Here's a more thorough breakdown of what's happening:

  • An r before a string literal means the string is a "raw string". It prevents Python from interpreting characters as an escape sequence. For instance, r"\n" is a slash followed by the letter n, rather than being interpreted as a single newline character. I like to use raw strings for my regex patterns, even though it's not always necessary.
  • the parentheses surrounding \w*-d is a capturing group. It indicates to the regex engine that the contents of the group should be saved for later use.
  • the sequence \w means "any alphanumeric character or underscore".
  • * means "zero or more of the preceding item". \w* together means "zero or more alphanumeric characters or underscores".
  • -d means "a hyphen followed by the letter d.

All together, (\w*-d) means "zero or more alphanumeric characters or underscores, followed by a hyphen and the letter d. Save all of these characters for later use."

The second string describes what the matched data should be replaced with. "\1" means "the contents of the first captured group". The parentheses are just regular parentheses. All together, (\1) in this context means "take the saved content from the captured group, surround it in parentheses, and put it back into the string".


If you want to match more characters than just alphanumeric and underscore, you can replace \w with whatever collection of characters you want to match.

>>> re.sub(r"([\w\.\[\]]*-d)", r"(\1)", "{{startingHere[zero1].my_string-d }}")
'{{(startingHere[zero1].my_string-d) }}'

If you also want to match words ending with "-d()", you can match a parentheses pair with \(\) and mark it as optional using ?.

>>> re.sub(r"([\w\.\[\]]*-d(\(\))?)", r"(\1)", "{{startingHere[zero1].my_string-d() }}")
'{{(startingHere[zero1].my_string-d()) }}'
2 of 2
0

If you want the bracketing to only take place inside double curly braces, you need something like this:

re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

Breaking that down a bit:

# the target pattern
r'({{\s*)([^}]*-d)(\s*}})'
# ^^^^^^^ capture group 1, opening {{ plus optional space
#        ^^^^^^^^^ capture group 2, non-braces plus -d
#                 ^^^^^^^ capture 3, spaces plus closing }}

The replacement r'\1(\2)\3' just assembles the groups, with parenthesis around the middle one.

Putting it together:

import re

def quote_string_d(s):
    return re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

print(quote_string_d("this is my {{string-d}}"))
print(quote_string_d("this is my second{{ new_string-d }}"))
print(quote_string_d("this should not be quoted other_string-d "))

Output:

this is my {{(string-d)}}
this is my second{{ (new_string-d) }}
this should not be quoted other_string-d 

Note the third instance does not get the parentheses, because it's not inside {{ }}.

Find elsewhere
🌐
Better Stack
betterstack.com › community › questions › how-to-print-curly-brace-in-python-string
How do I print curly-brace characters in a string while using .format in Python? | Better Stack Community
February 2, 2023 - To get a substring of a string in Python, you can use the string slicing notation, which is string[start:end], where start is the index of the first character of the substring, and end is the index...
🌐
Reddit
reddit.com › r/askprogramming › python how to explicitly add parentheses to string math input to show pemdas
r/AskProgramming on Reddit: python how to explicitly add parentheses to string math input to show pemdas
March 11, 2024 -

All inputs and outputs are strings. I want to add parentheses to the string that would clearly reflect the correct pemdas. The program does not execute any input.

Previously I posted this question and people were wondering why I'm adding parentheses when python already has built-in pemdas. I know it may look redundant, but the output of this will be sent into another function that absolutely needs these parentheses to work. Again, this is not a calculator. All inputs and outputs are treated as strings and no math operations are actually being done.

I'm also aware that the symbol ^ is not for exponents in python, but it is the case in general usage. For example, to specify y=x to the third, you'd type y=x^3 into desmos to graph it. This is also what the user will be entering into my program.

Take this for example:

2/s^3+1

We evaluate s^3 first, so that becomes (s^3), then we do the divide, so the output should be:

(2/(s^3))+1

Another way to think about this is the output is the string representation what python will interpret the input as, if python were to calculate the math expression. Even if the input doesn't have parentheses, python will interpret it with parentheses added according to pemdas. Now, for my program, instead of calculating the expression, I want the output to be the interpreted expression itself.

More examples:

Input: 50/2t
Output: (50/2)t
Input: a/b/c
Output: (a/b)/c
Input: 3^5t+3
Output: ((3^5)t)+3
Input: sqrt2/3
Output: (sqrt2)/3
Input: c_1+2  #c sub 1 plus 2
Output: (c_1)+2

Somehow I need to parse the math input, figure out the order of operations, and add parentheses to clearly reflect that. I also should be mindful if the original input already has parentheses, and my program needs to respect that and add more parentheses for clarification if necessary. Note here my program does not include any assumed parentheses.

🌐
Edlitera
edlitera.com › blog › posts › python-parentheses
Python Parentheses Cheat Sheet | Edlitera
This gives you an easy way to precisely assign variable values to certain spots in a string, and even to manipulate those same values. Example of assigning variable values using f-strings in Jupyter notebook: In this article, I've demonstrated some of the different uses for standard parentheses, square brackets, and curly braces in Python that you can use as a cheat sheet.
🌐
Django CAS
djangocas.dev › blog › python › python-literal-curly-braces-in-f-string
Python: How to print literal curly brace { or } in f-string and format string
July 10, 2024 - The parts of the string outside curly braces are treated literally, except that any doubled curly braces '{{' or '}}' are replaced with the corresponding single curly brace. A single opening curly bracket '{' marks a replacement field, which starts with a Python expression.
🌐
Runestone Academy
runestone.academy › ns › books › published › fopp › Sequences › IndexOperatorWorkingwiththeCharactersofaString.html
6.3. Index Operator: Working with the Characters of a String — Foundations of Python Programming
The expression in brackets is called an index. An index specifies a member of an ordered collection. In this case the collection of characters in the string. The index indicates which character you want. It can be any integer expression so long as it evaluates to a valid index value. Note that indexing returns a string — Python has no special type for a single character.
🌐
YouTube
youtube.com › edlitera
How to Use Curly Braces in Python - YouTube
Welcome back to the third part in our Python Parentheses Tutorial! We continue with curly braces in Python, which are used to create dictionaries, dictionary...
Published   April 15, 2023
Views   3K
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › number-of-ways-to-insert-two-pairs-of-parentheses-into-a-string-of-n-characters
Number of ways to insert two pairs of parentheses into a string of N characters - GeeksforGeeks
March 10, 2022 - // Java implementation of the approach import java.util.*; class GFG { // Function to return the number of ways // to insert the bracket pairs static int cntWays(String str, int n) { int x = n + 1; int ways = x * x * (x * x - 1) / 12; return ways; } // Driver code public static void main(String []args) { String str = "ab"; int n = str.length(); System.out.println(cntWays(str, n)); } } // This code is contributed by Rajput-Ji ... # Python3 implementation of the approach # Function to return the number of ways # to insert the bracket pairs def cntWays(string, n) : x = n + 1; ways = x * x * (x * x - 1) // 12; return ways; # Driver code if __name__ == "__main__" : string = "ab"; n = len(string); print(cntWays(string, n)); # This code is contributed by AnkitRai01