2010-06-24 91 views
1

我有一个字符串,如下所示:的Python:问题处理字符串

names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann" 

假设的字符串名称具有名称和NAME属性。

如何编写函数is_name_attribute(),该函数检查值是否为名称属性?这是is_name_attribute('fred')应该返回True,而is_name_attribute('gauss')应该返回False。

此外,如何创建分隔的字符串包含只有名称即属性逗号,

"fred, wilma, barney" 
+0

你的意思是“is_name_attribute( '高斯' )“在你的例子? – Constantin 2010-06-24 13:07:29

+0

@康斯坦丁:良好的呼唤;我已更新。 – FunLovinCoder 2010-06-24 13:36:22

回答

5

事情是这样的:

>>> names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann" 
>>> pairs = [x.split(':') for x in names.split(", ")] 
>>> attrs = [x[1] for x in pairs if x[0]=='name'] 
>>> attrs 
['fred', 'wilma', 'barney'] 
>>> def is_name_attribute(x): 
...  return x in attrs 
... 
>>> is_name_attribute('fred') 
True 
>>> is_name_attribute('gauss') 
False 
+0

+1对于非常地道的python – 2010-06-24 13:00:53

+0

非常感谢! – FunLovinCoder 2010-06-24 13:59:15

-1

我想在一个字符串写入ALS这玩意不是最好的解决方案,但是:

import re 

names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann" 

def is_name_attribute(names, name): 
    list = names.split() 
    compiler = re.compile('^name:(.*)$') 
    for line in list: 
     line = line.replace(',','') 
     match = compiler.match(line) 
     if match: 
      if name == match.group(1): 
       return True 
    return False 

def commaseperated(names): 
    list = names.split() 
    compiler = re.compile('^name:(.*)$') 
    commasep = "" 
    for line in list: 
     line = line.replace(',','') 
     match = compiler.match(line) 
     if match: 
      commasep += match.group(1) + ', ' 
    return commasep[:-2] 

print is_name_attribute(names, 'fred') 
print is_name_attribute(names, 'gauss') 
print commaseperated(names) 
+0

真的很痛 – unbeli 2010-06-24 13:03:11

0

还有其他方法可以做到这一点(正如您从答案),但也许是时候学习一些Python列表魔术了。

>>> names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann" 
>>> names_list = [pair.split(':') for pair in names.split(', ')] 
>>> names_list 
[['name', 'fred'], ['name', 'wilma'], ['name', 'barney'], ['name2', 'gauss'], ['name2', 'riemann']] 

从那里,这只是一个检查的情况。如果你正在寻找一个特定的名称:

for pair in names_list: 
    if pair[0] == 'name' and pair[1] == 'fred': 
     return true 
return false 

并加入只是名字版本:

>>> new_name_list = ','.join([pair[1] for pair in names_list if pair[0] == 'name']) 
>>> new_name_list 
'fred,wilma,barney' 
0

简单的正则表达式匹配:

>>> names = re.compile ('name:([^,]+)', 'g') 
>>> names2 = re.compile ('name2:([^,]+)', 'g') 
>>> str = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann" 
>>> 'fred' in names.findall(str) 
True 
>>> names.findall(str) 
['fred', 'wilma', 'barney']