Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strip() to remove only one element

Tags:

python

I have a word within two opening and closing parenthesis, like this ((word)). I want to remove the first and the last parenthesis, so they are not duplicate, in order to obtain something like this: (word).

I have tried using strip('()') on the variable that contains ((word)). However, it removes ALL parentheses at the beginning and at the end. Result: word.

Is there a way to specify that I only want the first and last one removed?

like image 875
Me All Avatar asked Dec 08 '22 13:12

Me All


2 Answers

For this you could slice the string and only keep from the second character until the second to last character:

word = '((word))'
new_word = word[1:-1]
print(new_word)

Produces:

(word)

For varying quantities of parenthesis, you could count how many exist first and pass this to the slicing as such (this leaves only 1 bracket on each side, if you want to remove only the first and last bracket you can use the first suggestion);

word ='((((word))))'
quan = word.count('(')
new_word = word[quan-1:1-quan]
print(new_word)

Produces;

(word)

like image 176
Nordle Avatar answered Dec 21 '22 01:12

Nordle


You can use regex.

import re
word = '((word))'
re.findall('(\(?\w+\)?)', word)[0]

This only keeps one pair of brackets.

like image 36
gofvonx Avatar answered Dec 20 '22 23:12

gofvonx