Categories
Programming

Converting a number into words, this time with Python and inflect.py

Teaching a person how to spell out numbers involves a lot of repetition. Tampa Bay’s own Jack Hartmann, whose children’s educational YouTube channel has over a million subscribers and 300 million views, knows this. He’s got a video that teaches kids the words for the numbers 0 through 10:

Don’t underestimate the power of videos for kids — Jack’s laughing all the way to the bank. This online estimator says that his YouTube channel should be earning about $70,000 every month, and keep in mind that his particular line of work has probably benefited from everyone being stuck at home. I may have to do something similar with the accordion when this software fad passes.

If you just wanted to be able to convert any number from 0 through 10 into word form in Python, you could use a list…

number_words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']

…and if you wanted the number 3 in word form, you’d use this:

# This is in the Python REPL
>>> number_words[3]
'three'

You wouldn’t want to take this approach for a larger set of numbers, and you probably wouldn’t want to code it yourself. Luckily, you don’t have to do this in Python, thanks to the inflect.py module.

Using inflect.py

Pythoninflect.py is a module that does all sorts of processing to make your programs’ text output grammatically correct. If you hate seeing output like this…

You have 1 items in your cart.

…or this…

You have a egg in your inventory.

…you can use inflect.py to automatically use the correct singular or plural form, use “a” or “an” when appropriate, and so much more.

(I’ll cover inflect.py in greater detail in a future article.)

In addition to all these grammatical goodies, inflect.py can also be used to convert numbers to words.

To use inflect.py, you’ll need to install it first. The simplest way to do so is with pip:

pip install inflect

Once installed, you can use it in your Python programs. Here’s an example:

import inflect

inflector = inflect.engine()

words = inflector.number_to_words(54321)
print(words)

It produces this output:

fifty-four thousand, three hundred and twenty-one

The number_to_words() method has a number of optional parameters that are useful in certain circumstances. For instance, there’s the boolean wantlist parameter, which causes the word output to be broken into “chunks”:

words = inflector.number_to_words(54321, wantlist=True)

It produces this output:

[‘fifty-four thousand’, ‘three hundred and twenty-one’]

Suppose you want the number to be converted into its individual digits as words. You’d use the group parameter:

# This is in the Python REPL

>>> inflector.number_to_words(54321, group=1)
'five, four, three, two, one'

>>> inflector.number_to_words(54321, group=2)
'fifty-four, thirty-two, one'

>>> inflector.number_to_words(54321, group=3)
'five forty-three, twenty-one'

What if you’re using the group parameter set to 1, but want to get all UK English and have it use the word “naught” for zero? Or maybe you want your program to sound like a film noir gangster and say “zip” instead? Or you want it recite a phone number and say “oh”? That’s what the zero parameter is for:

# This is in the Python REPL

>>> inflector.number_to_words(13057, group=1, zero='naught')
'one, three, naught, five, seven'

>>> inflector.number_to_words(13057, group=1, zero='zip')
'one, three, zip, five, seven'

>>> inflector.number_to_words(8675309, group=1, zero='oh')
'eight, six, seven, five, three, oh, nine'

The one parameter does the same thing, but for the digit 1:

# This is in the Python REPL

>>> inflector.number_to_words(13057, group=1, one='unity')
'unity, three, zero, five, seven'

Want to get all Star Trek? Use the decimal parameter to change the default decimal word to “mark”.

# This is in the Python REPL

>>> coordinates = inflector.number_to_words(123.789, group=1, decimal='mark')
>>> print(f"Ensign Crusher, set course to {coordinates}. Engage.")
Ensign Crusher, set course to one, two, three, mark, seven, eight, nine. Engage.

A lot of style guides tell you to spell out the numbers zero through ten, and use the number form for numbers 11 and greater. The threshold parameter makes this easy:

# This is in the Python REPL

>>> inflector.number_to_words(9, threshold=10)
'nine'

>>> inflector.number_to_words(10, threshold=10)
'ten'

>>> inflector.number_to_words(11, threshold=10)
'11'

Go ahead — import inflect.py and play with it. There’s a lot of power in that module, and it goes way beyond just converting words to numbers!

Also worth checking out

If you’re an iOS/macOS programmer, you’ll want to look at this article from a couple of days ago, Convert a number into words in a couple of lines of Swift.

Categories
Business Career Current Events Editorial Humor

THIS is how you tweet after a very public, somewhat embarrassing layoff

Tap to view Esther Crawford’s tweet.

Attention techies with a social media presence or looking to build one: THIS is what you post shortly after a very public, somewhat embarrassing setback. No bitterness, no recriminations, no finger-pointing — but clever self-deprecation.

In case you need context, the person behind the tweet is Esther Crawford, whom you might know from this tweet:

She’s one of the “Twitter 1.0” people who worked hard to get into Elon Musk’s good graces, which I wrote about in an earlier post, titled Lessons from the “sleeping bag director” at Twitter who just got laid off.

And in case you don’t know what the meme’s about, it’s made of stills from the TV series The Last of Us, and it features Joel, one of the protagonists, having panic attacks.

Tap to view this Twitter exchange.

Another good trick: answer what looks like a bad-faith question in a straightforward way, as if it were a good-faith question. Thomas Maxwell responded to Esther’s tweet with a question about sleeping bags, as shown above.

It was probably a good-faith question, judging from Maxwell’s Twitter timeline, but put yourself in Esther Crawford’s shoes. She’s probably still processing her very public layoff and dealing with slings and arrows from critics. In her position — and even as an observer — Maxwell’s question could easily be seen as a bad-faith barb.

Crawford did the right thing: she answered it as if it were a legitimate, good-faith question. This has a double-advantage:

  • If it is indeed a good-faith question, she’s just answered it.
  • If it’s a bad-faith question, it shows grace. Or if you prefer a more Machiavellian, it highlights the attacker’s dickishness.
Categories
Career Meetups Tampa Bay

High Tech Connect’s March Tech Fest at Rapid7 — TONIGHT!

Rapid7 and High Tech Connect are teaming up to have a tech fest in Rapid7’s new office starting at 5:15 p.m.! If you’re looking for work, you’ll want to check this out, as there’ll be networking, an open resume review and Rapid7 hiring update and overview. Find out more and register here!

What’s High Tech Connect?

High Tech Connect is a meetup group whose goal is to facilitate connections in the Tampa Bay technology community. They do this by holding monthly “Tech Fests,” which include a number of companies, including a not-for-profit, a start-up, and 3 or 4 for-profit businesses.

It’s a great way to catch up with your friends in the tech community, make new friends, and find out what’s going on here in “The Other Bay Area.”

Tap the photo to see the accompanying article.

Here’s a true story about an opportunity that started at High Tech Connect: In the summer of 2019, I was looking for work and decided to attend the July High Tech Connect event. I ran into my friend Tracy Ingram at the gathering, and we got to talking. A little bit into the conversation, I asked Tracy “Hey, do you want to go on StartupBus this year?”

He said yes. We went on StartupBus, formed a team (pictured above), made it to the finals, and were the first runner-up. I parleyed that into a mobile development job at Lilypad, and then later, into my current job as a Senior Developer Advocate at Okta.

Long story short: it pays to go to events like High Tech Connect!

What’s Rapid7?

Rapid7 are a security company, and as a reader of this blog, you’ve probably heard of their pentesting tool, Metasploit, their digital forensics and incident response tool, Velociraptor, or their threat intelligence tool, Threat Command.

What’s happening at this event?

For starters, they’re showing off their new office space in Channelside, located between the Florida Aquarium and the Channelside Bay Plaza.

It’s also a recruiting party. Rapid7 is hiring! You can see the list of current jobs here, and here’s a list of future roles currently not on their site:

  • Technical Support Engineer
  • Salesforce Senior Solution Architect
  • Salesforce Engineer
  • (Senior) Business Systems Analysts
  • Product Manager
  • Product Manager, IT
  • Netsuite Administrator
  • Product Operations Manager
  • Senior Software Engineer
  • Lead Software Engineer
  • Software Engineer II
  • Principal Software Engineer
  • Data Engineer

Finally, it’s a networking event. That’s why I’ll be there!

Does it cost anything? Do I need to register?

  1. It’s free!
  2. It would be best if you registered — and you can do it here!
Categories
Meetups Tampa Bay What I’m Up To

Scenes from last night’s “Coders, Creatives, and Craft Beer”

Last night, which was also the last night in February, the Coders, Creatives, and Craft Beer meetup took place in Seminole Heights at the Corner Club.

Anitra and I arrived a little bit before the starting time, 6:00 p.m., and had the back patio all to ourselves:

Tap to view at full size.

The crowd arrived soon after, the sun set, and we got down to the business of talking about all sorts of things, from ChatGPT to a business idea so crazy it just might work to Tampa’s growing scene of tech events to cycling clubs to music, and so on.

Tap to view at full size.

Coders, Creatives, and Craft Beer is a pretty good summary of what this meetup group is all about. There are no presentations, lectures, or workshops. Instead, it’s just people getting together at an interesting Tampa Bay venue, tasting what comes out of the taps and kitchen, and talking about what interests us, what we’re working on, and what we’d like to work on.

Tap to view at full size.

I like to refer to the meetup’s general philosophy as “All conversations, no presentations.” The goal is to make new friendships and maintain current ones, exchange information, help each other solve problems, and if we’re really lucky, Tampa Bay’s next great endeavor — maybe a technological one, maybe a creative one, maybe even both — will come about because people met here.

Tap to view at full size.

The Corner Club is one of Seminole Heights’ many hidden gems. They’re a neighborhood café with lots of great food prepared from scratch (we recommend the papas bravas potatoes), an interesting drinks selection — with and without alcohol, including some really good coffee — and even local artists’ works on the wall for sale. I really like their outdoor space in the back, which is generally where we hold events when we’re there.

We hold Coders, Creatives, and Craft Beer meetups monthly, and we’ll announce the March event shortly. Thanks to everyone who came out last night — and yes, we’ll have more get-togethers soon!

Categories
Business

Hey, LinkedIn: I fixed your stupid title!

LinkedIn highlighted a Wall Street Journal article titled As Americans Work from Home, Europeans and Asians Head Back to the Office with their own title: US Lags on RTO (where “RTO” means “return to office”).

Here’s my suggestion for a much better title: US Leads in WFH (where “WFH” means “work from home”).

Categories
Mobile Programming

Convert a number into words in a couple of lines of Swift

https://giphy.com/gifs/whoa-hd-tim-and-eric-xT0xeJpnrWC4XWblEk

Converting a number into its word form — for example, converting 1,234,456 into one million, two hundred and thirty-four thousand, four hundred and fifty-six — used to be a really painful exercise in programming. These days, there are libraries that save you from having to do this, and in the case of Swift, this functionality is built into its standard library in the form of the NumberFormatter class. Not only will it convert numbers into words, but it will also do so for many languages!

Open a Swift playground in Xcode and enter the following code:

// Swift

let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
let number = 87654
let spelledOutNumber = formatter.string(for: number)!
print("\(number) spelled out is \(spelledOutNumber).")

Run the playground code, and you’ll see this:

87654 spelled out is eighty-seven thousand six hundred fifty-four.

Having come from the world of C, where you format strings using printf() and formatting strings, and later from other languages where you use whatever formatting method its string class provides, I’ve ignored most of Swift’s classes that derive from Formatter — with one notable exception: DateFormatter, which is indispensable when working with dates and times.

I’m now looking for an excuse to use this capability.

As I typed “DateFormatter” a couple of paragraphs above, I remembered that DateFormatter had a locale property. It’s for ensuring that any dates you present are in the correct form for the locale:

I wondered:

  • Does NumberFormatter have a locale property?
  • What happens if I changed it to something other than my system’s default of US English?

So I changed the code in my playground to the following:

// Swift

let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
formatter.locale = Locale(identifier: "fil_PH")
let number = 87654
let spelledOutNumber = formatter.string(for: number)!
print("\(number) spelled out in Filipino is \(spelledOutNumber).")

I ran the code and saw this…

87654 spelled out in Filipino is walóng pû’t pitóng libó’t anim na daán at limáng pû’t ápat.

…and my response was “Ay nako!” (translation: OMG!)

How about Korean?

// Swift

let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
formatter.locale = Locale(identifier: "ko_KR")
let number = 87654
let spelledOutNumber = formatter.string(for: number)!
print("\(number) spelled out in Korean is \(spelledOutNumber).")

The output:

87654 spelled out in Korean is 팔만 칠천육백오십사.

My response: 세상에 (“Sesange!”, which is pretty much Korean for OMG!)

Try it out!  You might find this list of iOS locale string identifiers useful.

Tampa Bay Apple Coding Meetup (Tampa, FL) | Meetup

Speaking of Swift development, I’m restarting the Tampa Bay Apple Coding Meetup in the next few weeks. Watch this space, and if you’re interested, join the meetup group!

Categories
Business Career Current Events Editorial

Lessons from the “sleeping bag director” at Twitter who just got laid off

You may remember this tweet from a little less than four months ago:

Tap to view the original tweet.

The tweeter of that viral post and sleeper in the photo is Esther Crawford, Director of Product Management at Twitter — or at least she was. This weekend, she and at least 50 other employees were laid off.

She was recently the subject of an article in the Financial Times on January 24th (barely over a month ago) titled The rise of Esther Crawford in Elon Musk’s ‘hardcore’ Twitter. It tells the story of how she managed to become one of the few pre-Musk employees to parley their way into becoming one of “Space Karen’s” trusted lieutenants and in charge of several initiatives to make the company profitable, including Twitter Blue.

Her “sleeping bag” tweet raised a lot of eyebrows, including this short, yet spot-on response from Grady Booch, one of the patron saints of software development (and object-oriented programming in particular):

Tap to view the original tweet.

Crawford followed up with a multiple-tweet response:

[1] Since some people are losing their minds I’ll explain: doing hard things requires sacrifice (time, energy, etc). I have teammates around the world who are putting in the effort to bring something new to life so it’s important to me to show up for them & keep the team unblocked.

[2] I work with amazingly talented & ambitious people here at Twitter and this is not a normal moment in time. We are less than 1wk into a massive business & cultural transition. People are giving it their all across all functions: product, design, eng, legal, finance, marketing, etc

[3] We are and we use the hashtag to show it, which is why I retweeted with — a cheeky nod to fellow Tweeps. We’ve been in the midst of a crazy public acquisition for months but we keep going & I’m so proud of our strength & resilience.

[4] I love my family and I’m grateful they understand that there are times where I need to go into overdrive to grind and push in order to deliver. Building new things at Twitter’s scale is very hard to do. I’m lucky to be doing this work alongside some of the best people in tech. 💙

And it was great to see this follow-up from her supportive husband. I’m a firm believer that a marriage is a team, and kudos to Bob Cowherd for this tweet:

Tap to view the original tweet.

I have nothing but respect for Crawford’s drive, determination, and willingness to put in “crunch time.” I have nothing but praise for Cowherd’s supportiveness. Having worked for similarly careless, callous, and capricious bosses — they just didn’t come up from apartheid emerald money — I believe that Crawford’s intense dedication was wasted on Elon Musk.

My recommendation to any Twitter employee back in November was to leave, as I said in my November 7 post (5 days after Crawford’s “sleeping bag” tweet), Advice to laid-off Twitter employees being asked to come back. It even ends with the “sleeping bag” photo and this line:

If you can afford not to, don’t go back. You’re being asked to go back to Hell.

Some people on Twitter were more blunt — and in hindsight, prescient:

Tap to view the original tweet.
Tap to view the original tweet.
Tap to view the original tweet.

Loyalty to a company

I’ve had more than a few conversations — often over drinks, so these are backed by in vino veritas — where someone says that loyalty to a company is a sucker’s game. I think the truth is a little more nuanced than that.

A certain degree of loyalty to an employer who has earned it is actually a good thing. You’re more likely to be happy at work, and that’s important, as you’re that’s how you’re going to spend half your waking life from Monday through Friday. With this kind of loyalty comes two-way trust, and as Steven Covey puts it: Without trust, we don’t truly collaborate; we merely coordinate or, at best, cooperate. It is trust that transforms a group of people into a team.

I like and trust the company I work for and the team I work on. In fact, looking at the teams I’ve worked with in the past decade, the current one is my favorite. I like my manager, my manager’s co-managers, my “skip-level” manager, and the various C-level people, most of whom I’ve had the chance to meet (and even play accordion for). They have my loyalty — within reason — because I know that I also have their reciprocal loyalty — also within reason.

It’s clear to me that the organization isn’t a family. It’s a publicly-owned corporation that operates in the present-day economy. My relationship with the company is pleasant, cordial, and thanks to its culture, convivial, but I know it’s also transactional. Implicit in the employment contract between me and the company is the understanding that the basis of our relationship is that I give them my time and effort and they give me money.

Even with co-workers, managers, and C-level execs who I feel conduct themselves with decency and honor, my loyalty — which is considerable; I have Auth0 stickers on my accordion — is given with reasonable limits.

I would not extend that same loyalty to less decent, less honorable people. And I would most certainly not extend that loyalty to a vaingloriously venal weasel like Elon Musk.

Crawford’s “loyalty” was a gamble

David Xanatos, the clever, scheming villain from Gargoyles, and inspiration behind the “Xanatos Gambit” trope on TV Tropes.

While I am not in possession of the magic glasses that lets me see people’s true intentions, I’ve seen shit. And from the moment that Musk walked into Twitter HQ with a sink for comedic effect, Crawford has been doing exactly what one should do to get into the good graces of a petty, vengeful narcissist (who views most people as NPCs) that just spent billions on a criticism factory.

Consider this bit from the Financial Times piece:

When Musk first came to the San Francisco headquarters just before the deal closed, Crawford introduced herself in the Perch, Twitter’s on-site coffee shop, and secured a one-on-one meeting to discuss her ideas around payments and creators, according to multiple people familiar with the encounter.

And that “sleeping bag” photo? In the well-lit conference room? That’s somehow pristine clean even though everyone was in crunch mode? That ain’t no candid shot.

Tap to view the original tweet.

Also consider that Crawford grew up in a cult. In that kind of environment, you probably learn a couple of tricks on how to handle leaders who think they are the spokespeople for a higher power, or worse still, think they are that higher power.

Lest you think that I’m engaging in hyperbole by calling Elon Musk a narcissist, remember that he was so incensed that his Super Bowl tweet got only 9 million impressions compared to Joe Biden’s nearly 29 million that a “high urgency” message to @here on Twitter’s Slack was made to “any people who can make dashboards and write software” at 2:36 a.m. on the morning after the game. And let’s not forget that at a meeting to discuss the “lack of engagement” with his tweets, an engineer was fired for suggesting that public interest in Elon’s tweets had peaked and was now dropping.

I have worked at places whose mission I believed in, but whose management I did not. I believe that Crawford’s was a similar situation. And I took a similar approach, all the while readying not just Plan B, but the additional Plans C through G.

Keep this in mind…

Many people are going to dunk on Crawford for the next couple of days. Some of them will be from the Elon Musk fan club, who will say that she simply failed to deliver. Others will be Musk detractors, who will say that it’s what you get for working an egomaniacal autocrat.

Many of them will be the sort whose tendencies are to punish women for the sin of being ambitious. Keep that in mind.

So what are the lessons here?

Even if the purpose of this post was to dunk on Esther Crawford — and it isn’t — I would still be “punching up.”

Tap to read an early TechCrunch article about Squad.

Crawford came to Twitter by way of acquisition. Twitter bought the video chat startup she founded, Squad, in late 2020. While the amount wasn’t disclosed, a look at Twitter acquisitions shows that they haven’t bought any company for less than double-digit millions. She has a great resume, she can always point to that profile in Financial Times, and she’ll likely be featured in a “What Next?” piece in some other tech or business publication very soon. She can even trade on the story that she worked with tech’s biggest jackass.

Simply put: Crawford will most likely be fine.

This article is not really about her, nor is it for her. It is, most likely, for you, especially if you don’t have a six- or seven-figure cushion to fall back on when the going gets brutal at work.

In my opinion, the lessons to take away are:

  1. If you can help it, don’t work for assholes. If the option is available to you, try to work for and with people with at least some character. And try not to work for self-serving, whim-governed, spoiled emperors.
  2. If it can’t be helped and you have to work for an asshole, learn to manage them. And while you’re at it, formulate a plan to minimize your exposure from said asshole, or get away from them altogether.
  3. Favor high-trust environments over low-trust ones. Yes, there are a number of high-paying low-trust environments out there. In fact, the high pay is often used as a way of making up for the low trust. They might be great for your bank account in the short term, but they’re terrible in the long term.
  4. There’s a fine line between singing your company’s praises and bootlicking. Each of us has a different idea of where that line is drawn. And some of us will talk pretty loudly about it.
  5. Build a support network. A supportive spouse or partner can be a great help if you’re working at someplace like the current Twitter, and a network of peers can often be your key to escaping to a different organization.

Further reading