DEV Community

Robin Winslow
Robin Winslow

Posted on • Originally published at robinwinslow.uk

Tweet-counter: A module to calculate the length of a tweet

Originally published on my blog.

I just published a new Python package: tweet-counter (repo).

If you want to automate posting of tweet using Python, it's pretty important to know if your tweet exceeds the 280-character limit.

It turns out, working this out is non-trivial, as Twitter has a few rules around how it count's characters. These are basically:

  • Twitter will convert anything that looks like a URL (with a valid TLD - e.g. example.ae) into a Twitter short link, and count it as taking up exactly 23 characters
  • Twitter counts emoji and any unicode character above U+2037 as each taking up 2 characters

To it's credit, Twitter provides official open-source libraries for calculating tweet length.

But there isn't a library for Python that I could find. So I made one. It's probably far from perfect, but it does at least take into account the top two conditions, which should cover most common English-language use cases.

$ pip3 install tweet-counter
$ count-tweet "Otters πŸ‘ͺ otters π—Όπ˜π˜π—²π—Ώπ˜€ otters otters.com/otters"
60
Enter fullscreen mode Exit fullscreen mode

I'm hoping to use it in an automatic tool for turning blog posts into twitter threads that I'm working on.

Top comments (0)