正则表达式在开始和结束时替换特殊字符但不在中间

时间:2017-01-19 13:04:57

标签: python regex

我有一个像

这样的输入字符串
str1 = [( hello world,good morning)]
str2 = ([ hello world,good morning])
str3 = [( hello world,(today) is good day])

并输出应为:

  

str1 =你好世界,早上好

     

str2 =你好世界,早上好

     

str3 =你好世界,(今天)是美好的一天

我需要一个正则表达式来替换开头和结尾处的特殊字符,但不能在字符串的中间替换。

帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

使用str.strip

>>> my_string = "[( hello world,good morning)]"
>>> my_string.strip("([ ])") # strips brackets and whitespace from both sides
'hello world,good morning'