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 Overflowpython - How to add round brackets to strings in column - Stack Overflow
arrays - Insert square brackets around specific words within a text string in Python? - Stack Overflow
Adding brackets to a list and sort it
regex - surrounding a pattern in python string with brackets - Stack Overflow
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)
Approach 1: Using direct Concatenation (Simpler)
df['Column_A'] = '(' + df['Column_A'] + ')'

Approach 2: Using apply() function and f-strings
df.Column_A.apply(lambda val: f'({val})')

Approach 3: Using map() function
df = pd.DataFrame(map(lambda val: f'({val})', df.Column_A))

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
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."
>>> 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
rbefore 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*-dis a capturing group. It indicates to the regex engine that the contents of the group should be saved for later use. - the sequence
\wmeans "any alphanumeric character or underscore". *means "zero or more of the preceding item".\w*together means "zero or more alphanumeric characters or underscores".-dmeans "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()) }}'
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 {{ }}.
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.
I am refreshing python skills after some time, I am getting confused when to use diff types of brackets, round, curly, or square
Any advice or tips on how to memorize or understand this?
Thanks
I'm confused about the use of the curly brackets in this code from a textbook. I thought the curly brackets are to call dictionaries. but first and last are not, am I right?
def get_formatted_name(first,last):
full_name=f"{first}{last}"
return full_name.title()
You need to double the {{ and }}:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
Here's the relevant part of the Python documentation for format string syntax:
Format strings contain “replacement fields” surrounded by curly braces
{}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{and}}.
Python 3.6+ (2017)
In the recent versions of Python one would use f-strings (see also PEP498).
With f-strings one should use double {{ or }}
n = 42
print(f" {{Hello}} {n} ")
produces the desired
{Hello} 42
If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
produces
{hello}
To escape curly braces, duplicate them:
>>> x="abc"
>>> f"{x} {{x}}"
'abc {x}'
You can also look at the PEP for more information: https://www.python.org/dev/peps/pep-0498/#escape-sequences
You need to use curly bracket twice if you are assigning variable value and once if you are putting on a value:
Class = "maximum"
s = f"""The code for {{{Class}}} is {{'3854-st56'}}"""
print(s)
The code for {maximum} is {3854-st56}