Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the rjust method leave a string unchanged?

I have 2 codes snippets in Python 3:

print(b'3'.rjust(4, b'0'))

b'0003'
length = str(len("str")).encode() # length as bytes
length.rjust(4, b'0') # trying to pad length
print(length)

b'3'

As I understand it, both should produce the same result as the first snippet. Why does the second snippet not work as expected?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

length.rjust returns a new string. Strings in Python cannot be modified in place. Try:

length = length.rjust(4, b'0')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading