简体   繁体   中英

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?

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

One of the solutions using regex:

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

See DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM