0
number = input("Enter the number:")
''' Let's suppose the entered number is 0145. Question is below.'''

I want to add a comma after 0. How can i do this?

451
  • 17
  • 3
  • 1
    What is your current output? What is the exact output you want? – quamrana Jul 30 '22 at 16:24
  • 1
    Are you looking for commas with long integers (e.g. 1,000) or somethng like "0,145" ?? – CodeMonkey Jul 30 '22 at 16:25
  • The output i want is 0,145 – 451 Jul 30 '22 at 16:35
  • 2
    Welcome to Stack Overflow! Please take the [tour] and read [ask]. `0145` isn't a valid `int`; it gets converted to just `145`. So the situation you're describing is not possible, unless you want something like `'0,' + str(number)`, but that seems silly. Please [edit] and clarify what you're trying to accomplish. Beware the [XY problem](https://meta.stackexchange.com/q/66377/343832). – wjandrea Jul 30 '22 at 16:37
  • 1
    Did you mean you want to add a character at a certain position in a string like [this](https://stackoverflow.com/questions/5254445/how-to-add-a-string-in-a-certain-position)? The `input()` function returns a string already. If you do `int(input(...` you will lose any leading `0` chars. – quamrana Jul 30 '22 at 16:38
  • Yes i know, i am trying to make it a decimal number in a string. Just i want is adding a comma after the first character of a string basically. – 451 Jul 30 '22 at 16:39
  • Thanks, quamrana. That is what i wanted. – 451 Jul 30 '22 at 16:41

1 Answers1

2

Use {:,} to format a number with commas in Python.

Example:

number = 1000
print(f"{number:,}")

Output:   1,000

If want a general purpose number formatter for numbers as strings that may include leading 0's then there is a solution using regular expressions here. If user enters "0145" and want to format that as "0,145" then you'd need to use the string input rather than converting to an integer which would drop any leading 0's.

CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
  • Well, this works. But what i want is that the value n should be a string. This doesn't seem work with a string value. – 451 Jul 30 '22 at 16:32