2012-10-30 67 views
0

我想分割這個字符串def Hello(self,event):,這樣只剩下Hello,分隔符首先是def,然後我猜():。我如何在Python中做到這一點?將字符串從一個點拆分到另一個(不同的分隔符)

+0

您是否嘗試過使用常用表達? – ChipJust

+0

嗯,你爲什麼要用「split」來做到這一點?似乎並不合適...... –

+0

你需要描述**它應該如何只留下''你好''... –

回答

1

我建議使用正則表達式這樣的事情(見其他例子),但在這裏回答你的問題的解決方案使用split

In [1]: str = "def Hello(self,event):" 
In [2]: str.split(' ')[1].split('(')[0] 
4

你在尋找類似

re.findall('^def ([^(]+)', 'def Hello(self, asdf):') 
+1

不需要'。* $'' –

+0

@Ωmega我只是喜歡有時候會盡頭 – mayhewr

+0

好吧,它還是不錯的,只是沒有針對性能進行優化:) –

2

使用正則表達式

^def\s+(\w+)\((.*?)\) 
0

下面是使用正則表達式一個選項:

import re 
re.search(r'def\s+([^)\s]*)\s*\(', your_string).group(1) 

例子:

>>> re.search(r'def\s+([^)\s]*)\s*\(', 'def Hello(self, asdf):').group(1) 
'Hello' 
>>> re.search(r'def\s+([^)\s]*)\s*\(', 'def Hello (self, asdf):').group(1) 
'Hello' 

說明:

def   # literal string 'def' 
\s+   # one or more whitespace characters 
(   # start capture group 1 
    [^)\s]*  # any number of characters that are not whitespace or '(' 
)   # end of capture group 1 
\s*   # zero or more whitespace characters 
\(   # opening parentheses 
相關問題