2012-10-30 68 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 
相关问题