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?

7
  • 1
    What is your current output? What is the exact output you want? Commented Jul 30, 2022 at 16:24
  • 1
    Are you looking for commas with long integers (e.g. 1,000) or somethng like "0,145" ?? Commented Jul 30, 2022 at 16:25
  • The output i want is 0,145 Commented Jul 30, 2022 at 16:35
  • 2
    Welcome to Stack Overflow! Please take the tour and read How to 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. Commented Jul 30, 2022 at 16:37
  • 1
    Did you mean you want to add a character at a certain position in a string like this? The input() function returns a string already. If you do int(input(... you will lose any leading 0 chars. Commented Jul 30, 2022 at 16:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.