skip to Main Content

I’m currently trying to learn the Twitter API and I’m working on a method that will prepare a string that’s separated by a | for a threaded post and append the number of tweets to each element of the list. So as an example:

tweet_thread = "this is going|to be a multipart|tweet thread about python"
tweets = (tweet_thread.split('|'))
tweet_list = []
count = 1
total = len(tweets)
if total > 1:
    for item in tweets:
        tweet_count = " " + str(count) + "/" + str(total)
        tweet_list.append(item + tweet_count)
        count +=1

This returns what I want:

['this is going 1/3', 'to be a multipart 2/3', 'tweet thread about python 3/3']

But I’m thinking there has to be a much more elegant/pythonic way of doing this, perhaps with a comprehension?

Any guidance would be greatly appreciated!

Thanks

2

Answers


  1. Using enumerate :

    [elem+' '+str(i+1)+'/3' for i, elem in enumerate(tweet_thread.split('|'))]
    
    Login or Signup to reply.
  2. Use f-string and list comprehension with enumerate:

    tweet_thread = tweet_thread.split('|')
    result = [f"{i} {index}/{len(tweet_thread)}" for index,i in enumerate(tweet_thread,1)]  # not hardcoding length here.   
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search