brandon carl

software engineer

Python: Stringify Integer with Commas

This problem came from a comment I saw on /r/Python the other day, posted by jwegan.

I tend to browse the Python subreddit every so often to see what’s new in the Python world and what other problems people are running into. I really love it when I can contribute to the discussion of a question or problem and potentially help out a person learning Python, just like I was helped out when I first learned the language.

This one seemed simple enough, so I figured I would give it a shot and see what I could come up with. I like doing fun problems like these in my free time as a way to break free from some of the larger projects on my plate.

The Comment

Another fun python variable manipulation question is: given an int, write a one liner that returns the string representation of the int, but with a comma every three decimal places starting from the right. (i.e., 1 return “1”, and 1000 returns “1,000”)

(Rules: the one line cannot use anything that has to be imported, and cannot use any string formatting)

-jwegan

Test-Driven Development

I started out by setting up some basic tests. (Yay TDD!)

Multi-Line Solution

Then I went to work on a general, multi-line solution.

One-Liner

And finally, I refactored the multi-line solution into a less-readable, but valid one-liner.

Thanks for reading! If you want to talk to me about this, feel free to comment, e-mail me, or find me on my various social networks.