使用strip()仅删除一个元素

时间:2018-10-09 14:03:57

标签: python

我在两个左括号和右括号中有一个字,例如((word))。 我想删除第一个和最后一个括号,因此它们不是重复的,以便获得如下内容:(word)

我尝试对包含strip('()')的变量使用((word))。但是,它会删除开头和结尾的所有括号。结果:word

有没有一种方法可以指定我只希望删除第一个和最后一个?

7 个答案:

答案 0 :(得分:4)

为此,您可以对字符串进行切片,仅保留从第二个字符到第二个到最后一个字符:

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

产生:

(word)

对于不同数量的括号,您可以count首先存在多少括号,然后将其传递给切片(如果要删除,则此留出的每一边只有1个括号) 您可以使用第一个建议的第一个和最后一个括号);

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

生产;

(word)

答案 1 :(得分:3)

您可以使用正则表达式。

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

这只会保留一对括号。

答案 2 :(得分:2)

您可以replace两次加双括号,并将两个操作的max参数设置为1

print('((word))'.replace('((','(',1).replace('))',')',1) )

但是,如果出现更多双括号的话,这将不起作用 也许在替换结尾的字符串之前反转字符串会有所帮助

t= '((word))'
t = t.replace('((','(',1)
t = t[::-1]  # see string reversion topic [https://stackoverflow.com/questions/931092/reverse-a-string-in-python]
t = t.replace('))',')',1) )
t = t[::-1]  # and reverse again

答案 3 :(得分:2)

代替使用str.replace,所以您将str.replace('(','',1)

基本上,您将用'替换所有'(',但是第三个参数将仅替换指定子字符串的n个实例(作为参数1),因此,您将仅替换第一个'('

阅读文档:

替换(...)     S.replace(old,new [,count])->字符串

Return a copy of string S with all occurrences of substring
old replaced by new.  If the optional argument count is
given, only the first count occurrences are replaced.

答案 4 :(得分:1)

好吧,我为此使用正则表达式,并使用re.sub函数将一堆括号替换为一个括号

import re
s="((((((word)))))))))"
t=re.sub(r"\(+","(",s)
g=re.sub(r"\)+",")",t)
print(g)

输出

(word)

答案 5 :(得分:1)

尝试这个:

str="((word))"

str[1:len(str)-1]

print (str)

输出为= (word)

答案 6 :(得分:1)

尝试以下方法:

>>> import re
>>> w = '((word))'
>>> re.sub(r'([()])\1+', r'\1', w)
'(word)'
>>> w = 'Hello My ((word)) into this world'
>>> re.sub(r'([()])\1+', r'\1', w)
'Hello My (word) into this world'
>>> 
相关问题