2010-06-24 7 views
1

을 처리하는 문제는 문자열이있다.파이썬 다음과 같이 문자열

값이 이름 속성인지 확인하는 is_name_attribute() 함수를 작성하려면 어떻게합니까? is_name_attribute ('fred')는 True를 반환해야하지만 is_name_attribute ('gauss')는 False를 반환해야합니다. 또한

, 나는 이름, 즉 속성 만 구성된 문자열을 쉼표로 구분,이 같은

"fred, wilma, barney" 
+0

는 "하셨습니까 is_name_attribute ('가우스') "귀하의 모범에서? – Constantin

+0

@ 콘스탄틴 : 좋은 전화; 나는 갱신했다. – FunLovinCoder

답변

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 오 -이 - 관용적 인 비단뱀 –

+0

대단히 감사합니다! – FunLovinCoder

-1

을 나는 문자열에서 루게릭 병이 물건을 기입이 생각 최상의 솔루션은 아니지만,

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

0

다른 방법이 있습니다 (아마도 파이썬리스트 마법을 배울 때가왔다.

>>> 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']