2016-10-10 22 views
2

我想檢測的字符串括號,如果找到,取出托架和所有數據在括號如果在字符串中發現發現括號,然後取出支架和數據括號內

例如

Developer (12)

將成爲

Developer

編輯:請注意,字符串將是一個不同的長度/文每次,和括號不會永遠存在。

我可以使用類似

if '(' in mystring: 
    print 'found it' 

,但我會如何去除(12)檢測括號?

+0

https://docs.python.org/2/library/functions.html?highlight=slice#slice –

+0

你應該使用一個[正則表達式(https://docs.python.org/ 3 /庫/ re.html)。 –

+0

'slice(0,myString.index('('))' –

回答

3

您可以通過用戶正則表達式和替換它:我

>>> re.sub(r'\(.*?\)', '','Developer (12)') 
'Developer ' 
>>> a='DEf (asd() . as (as ssdd (12334))' 
>>> re.sub(r'\(.*?\)', '','DEf (asd() . as (as ssdd (12334))') 
'DEf . as)' 
+0

它不適用於嵌套括號。 –

+1

@ S.deMelo from op - _「yes always at the 「_。他明確指出他不需要支持嵌套括號 –

+0

@leaf當時情況並非如此 –

1

相信你想要的東西,這樣的

import re 
a = "developer (12)" 
print(re.sub("\(.*\)", "", a)) 
+0

這與以前的解決方案相同並且具有相同的限制 – brianpck

+0

它不會不能使用嵌套括號 –

+0

@brianpck我發佈了它,但沒有看到以前的答案,但是它與此類似。 –

0

因爲它總是在最後並沒有嵌套括號:

s = "Developer (12)" 
s[:s.index('(')] # or s.index(' (') if you want to get rid of the previous space too 
0

對於嵌套括號和字符串中的多個對,此解決方案可以工作

def replace_parenthesis_with_empty_str(str): 
    new_str = "" 
    stack = [] 
    in_bracker = False 
    for c in str : 
     if c == '(' : 
      stack.append(c) 
      in_bracker = True 
      continue 
     else: 
      if in_bracker == True: 
       if c == ')' : 
        stack.pop() 
       if not len(stack): 
        in_bracker = False 
      else : 
       new_str += c 
    return new_str 

a = "fsdf(ds fOsf(fs)sdfs f(sdfsd)sd fsdf)c sdsds (sdsd)" 
print(replace_parenthesis_with_empty_str(a)) 
相關問題