DEV Community

Robin Winslow
Robin Winslow

Posted on β€’ Originally published at robinwinslow.uk

3 1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay