0 votes
1 view
in Data Science by (18.3k points)

I am required to remove the elements within the square bracket of the string. However, I am unable to get my desired results.

Below is desired the output I am required to get:

Example of the Output

[[apple].png -> [.png

[apple]].png -> ].png

[[apple]].png -> [].png

[an]apple[adaykeeps]]the[[doctor]away.png -> apple]the[away.png

The methods I've used are mentioned below, but I am not able to get my required output:

Regex Method

file = re.sub(r'(\d*\D+\d*)\s+','',re.sub(r'{.+?#(\d+).\d+)}',r'(\1)',file));

SubString Method

openbracket = file.find('['); closebracket = file.find(']');

if len(file) > closebracket : file = file[0: openbracket:] + file[closebracket + 1::]

1 Answer

0 votes
by (36.8k points)

You can do this with the regex; your regex needs to match the [ followed by some of the numbers of non [ or ] characters until a ], and replacethe string with nothing:

import re

strings = ['[[apple].png', '[apple]].png', '[[apple]].png', '[an]apple[adaykeeps]]the[[doctor]away.png']

for s in strings:

    name = re.sub(r'\[[^][]*\]', '', s)

    print(name)

Output:

[.png

].png

[].png

apple]the[away.png

This code will replace the [] with the empty string ``; if this is not a desired behaviour change the * in the regex to a +.

If you are a beginner and want to know more about Python the do check out the python for data science course

Welcome to Intellipaat Community. Get your technical queries answered by top developers !

Categories

...