Alex Rivera | Logout

An elegant way to get hashtags out of a string in Python?

Asked 2011-06-13T14:04:54.540
12

I'm looking for a clean way to get a set (list, array, whatever) of words starting with # inside a given string.

In C#, I would write

var hashtags = input
    .Split (' ')
    .Where (s => s[0] == '#')
    .Select (s => s.Substring (1))
    .Distinct ();

What is comparatively elegant code to do this in Python?

EDIT

Sample input: "Hey guys! #stackoverflow really #rocks #rocks #announcement"
Expected output: ["stackoverflow", "rocks", "announcement"]

Edit
Report

1 Answer

10

the findall method of regular expression objects can get them all at once:

>>> import re
>>> s = "this #is a #string with several #hashtags"
>>> pat = re.compile(r"#(\w+)")
>>> pat.findall(s)
['is', 'string', 'hashtags']
>>> 
answered 2011-06-13T14:17:32.663

Your Answer