views:

72

answers:

4

I have a string as follows:

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

let's say the string names has name and name2 attributes.

How do I write a function, is_name_attribute(), that checks if a value is a name attribute? That is is_name_attribute('fred') should return True, whereas is_name_attribute('gauss') should return False.

Also, how do I create a comma separated string comprising of only the name attributes i.e.,

"fred, wilma, barney" 
+5  A: 

Something like this:

>>> 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
unbeli
+1 For oh-so-idiomatic python
Jamie Wong
@unbeli: Thanks very much!
swisstony
A: 

I think writing als this stuff in a String is not the best solution, but:

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)
TooAngel
that really hurts
unbeli
A: 

There are other ways of doing this (as you'll see from the answers) but perhaps it's time to learn some Python list magic.

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

From there, it's just a case of checking. If you're looking for a certain name:

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

And joining just the name versions:

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

Simple regexp matching:

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