7
\$\begingroup\$

This is my attempt to format a number and put commas where appropriate. I was wondering if this could be done in a simpler way.

It's used by calling format_string_number("123456789") and prints 123,456,789.

def format_string_number(st):
 inputVal = list(st)
 inputVal.reverse()
 returnVal = []
 for index, value in enumerate(inputVal):
 returnVal.insert(0,value)
 if (index+1) %3 == 0:
 returnVal.insert(0,",")
 if returnVal[0] == ",":
 returnVal.pop(0)
 print("".join(returnVal))
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 19, 2014 at 23:44
\$\endgroup\$
3
  • \$\begingroup\$ I don't know enough python to tell you whether directly dealing with strings would be possible and faster... However, your condition against the index could be written index % 3 == 2 and you'd avoid a +1 on each iteration. \$\endgroup\$ Commented Sep 20, 2014 at 2:48
  • \$\begingroup\$ Are you looking for a better way to do it manually, or would format(123456789, ",") suffice? \$\endgroup\$ Commented Sep 20, 2014 at 5:34
  • \$\begingroup\$ To build off the approach suggested by @DSM : format(int("123456789"), ",") \$\endgroup\$ Commented Sep 28, 2014 at 7:03

1 Answer 1

11
\$\begingroup\$

A few comments:

  1. It seems odd to write a function for formatting a number that takes a string as an argument;
  2. Your function doesn't currently deal with float numbers correctly (and, as it takes a string argument, you can't easily check isinstance(arg, int));
  3. Your function prints the output rather than returning it, severely limiting its usefulness; and
  4. You aren't compliant with the style guide.

Also, as pointed out in the comments, this is handled by format already, and can be used in str.format too:

>>> "Number: {:,}".format(123456.789)
'Number: 123,456.789'
answered Sep 20, 2014 at 7:30
\$\endgroup\$
3
  • \$\begingroup\$ using , is not locale aware \$\endgroup\$ Commented Jan 2, 2019 at 22:24
  • \$\begingroup\$ @user5359531 true! But nor was the original, and that requirement is not in the title or description. \$\endgroup\$ Commented Jan 2, 2019 at 22:32
  • \$\begingroup\$ I've made a new question here to address that, perhaps you could check it out. \$\endgroup\$ Commented Jan 2, 2019 at 23:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.