As3adTintin
As3adTintin

Reputation: 2476

Extract characters from string after last period

I have an orderedDict:

dict2.items():
[('A', <function __main__.percentile_50>),
 ('B', <function numpy.core.fromnumeric.sum>),
 ('C', <function numpy.core.fromnumeric.sum>),
 ('D', <function numpy.core.fromnumeric.mean>),
 etc...

I want to create a column that says what descriptive was used (percentile_50, sum, mean, etc.) I'm thinking of finding the last . and then grabbing the characters after it up until >. So I would end up with percentile_50, sum, sum, mean, etc.. Any suggestions?

Upvotes: 0

Views: 1702

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

One of the solutions using regex:

(?<=\.)([^.>]+)(?=>$)

See DEMO

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

If you have string in your tuples you can use split within a list comprehension :

>>> l=[('A', '<function __main__.percentile_50>'),
...  ('B', '<function numpy.core.fromnumeric.sum>'),
...  ('C', '<function numpy.core.fromnumeric.sum>'),
...  ('D', '<function numpy.core.fromnumeric.mean>')]
>>> 
>>> [(i,j.strip('>').split('.')[-1]) for i,j in l]
[('A', 'percentile_50'), ('B', 'sum'), ('C', 'sum'), ('D', 'mean')]

But if you have function objects you can use the __name__ attribute for your function to extract the names :

>>> [(i,j.__name__) for i,j in l]
[('A', 'percentile_50'), ('B', 'sum'), ('C', 'sum'), ('D', 'mean')]

Upvotes: 2

Related Questions