user7250276
user7250276

Reputation:

check if an item starts with a symbol in a tuple Python

a = {
    'a' : [
        ('a', '"Folks marched & protested for our right to vote." --@FLOTUS\n', 1477610322, 'TweetDeck', 545, 226),
        ('a', '"We urge voters to dump Trump" --@DenverPost', 1476205194, 'TweetDeck', 7165, 2225)
        ],
    'b:' : [
        ('b:', 'Join me in #Atlanta November 2. Details-  #YouIn? #JohnsonWeld\n', 1478034098, 'Hootsuite', 108, 51)
        ]
    }

for key, value in a.items():
    for item in value:
        #extract string beginning with #'s with the user (the users are a and b)

I'm trying to extract hashtags with the user indicated with it, from the tuple. I only know the method startswith but you cannot use it for tuples.

Upvotes: 0

Views: 1071

Answers (1)

bli
bli

Reputation: 8194

You can split a string using the split method, which by default splits on whitespaces:

s = 'Join me in #Atlanta November 2. Details-  #YouIn? #JohnsonWeld\n'
s.split() 
# ['Join', 'me', 'in', '#Atlanta', 'November', '2.', 'Details-', '#YouIn?', '#JohnsonWeld']

You can then use startswith on each resulting element to check if it is a hashtag, in a list comprehension:

[tag for tag in s.split() if tag.startswith("#")]
# ['#Atlanta', '#YouIn?', '#JohnsonWeld']

You can encapsulate this in a function for more readable code:

def get_hashtags_from_string(s):
    return [tag for tag in s.split() if tag.startswith("#")]

Upvotes: 1

Related Questions