0

I meet a problem about converting number to string.

I want to get a string "0100" from str(0100), but what I got is "64". Does any way I can do to get a string "0100" from 0100.

UPDATE

Thanks for many people's pointing out that the leading "0" is a indicator for octal. I know it, what I want is to convert 0100 to "0100", any suggestion?

Best Regards,

1
  • Re your update - you could just use oct(0100) but that's probably not your intention. Where are you obtaining the integer 0100 from? Are you reading it from somewhere? Perhaps there's better ways to solve this, but you'll need to provide us with some context to your problem. Commented Nov 3, 2012 at 7:35

5 Answers 5

1

Your first issue is that the literal "0100", because it begins with a digit 0, is interpreted in octal instead of decimal. By contrast, str(100) returns "100" as expected.

Secondly, it sounds like you want to zero-fill your numbers to a fixed width, which you can do with the zfill method on strings. For example, str(100).zfill(4) returns "0100".

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

Comments

1

The integer should be written as 100, not 0100.

You can format the string with leading zeros like this:

>>> "%04d" % 100
'0100'

Comments

0

In Python2, a leading 0 on a numeric literal signifies that it is an octal number. This is why 0100 == 64. This also means that 0800 and 0900 are syntax errors

It's a funny thing that's caught out many people at one time or another.

In Python3, 0100 is a syntax error, you must use the 0o prefix if you need to write a octal literal. eg. 0o100 == 64

Comments

0

You could just concatenate both strings so if you want 0100

res = str(0) + str(100)

that way res = '0100'

Comments

-1

Not sure if I understood the question... maybe you're looking for this:

'%04o' % 0100  # 0100

5 Comments

This solution breaks for many other cases. e.g. '%04o' % 1100 returns "2114"
This is Python2 Syntax and won't work with CPython from 2020. Don't teach this to people! Python3 way is using f-strings (e.g. f"{100:04o}"
@SV-97: look at the post date, dude
@georg Well Shit. Why was this in my feed then?
@SV-97 Because someone added an answer 8 hours ago.

Your Answer

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.