NathanK NathanK - 1 month ago 10
Python Question

Python random string selection

I am trying to select a random word that starts with a hashtag, Here is my current code and I have tried

random.choice()
, but it will only select one letter. I am guessing its because I am storing the results as one big string, maybe it needs a dictionary but I am still a little unsure how to do it.

trends1 = api.trends_place(1) # from the end of your code
# trends1 is a list with only one element in it, which is a
# dict which we'll put in data.
data = trends1[0]
# grab the trends
trends = data['trends']
# grab the name from each trend
names = [trend['name'] for trend in trends]
# put all the names together with a ' ' separating them
trendsName = ' '.join(names)


This returns

#NaFaltaDoQueFazerEu #Aliyaİzzetbegoviç #LawinPH + more


I want to randomly select a hashtag, but at the minute its choosing a random letter from the string, i.e. doing

random.choice(trendsName)


returns a random letter instead of a random hashtag

Answer

You would just need to call random.choice() on names instead of trendsName:

import random
random.choice(names)

random.choice() returns an element of a sequence. If your sequence is a string, then that element will be a single character from that string. However, if your sequence is a list, then that element will be a member of the list, which in the case of names, looks like it will be a hashtag.