Как добавить 0 перед числом python
Перейти к содержимому

Как добавить 0 перед числом python

  • автор:

�� Welcome!

Estefania Cassingena Navone

In this article, you will learn exactly why and what changed. You’ll be surprised to know that it has to do why the octal numeral system.

Amazing, right? �� Let’s dive into the details!

✅ Python 2 — Leading Zeros… Here We Go!

In this version of Python, you were able to add leading zeros to your liking without causing any errors. Expressions like these were allowed:

I’m sure that you must be thinking: why would they allow this if leading zeros don’t add anything to the result?

0000015 should be equivalent to 15, right? ��

⚠️ Not in Python 2! ��

The first zero in 0000015 acts like a “flag” �� that tells the Python interpreter that the number is expressed in the octal numeral system (base 8) instead of the decimal system that we usually work with (base 10).

This is why the interpreter returns the number 13 when we type 0000015. The number is converted from the octal numeral system to the decimal numeral system. (I included a brief explanation of this process below ��).

But how can we tell Python that this number is already in the decimal numeral system, and that the leading zeros shouldn’t change the result?

This is where Python 3 comes to the rescue! ��

✅ Python 3— Bye, Bye, Leading Zeros!

In Python 3, this is not a problem anymore because the “flag” �� is much clearer now to differentiate numbers in the octal numeral system. The number must start with 0o or 0O (zero followed by an “o” letter in lowercase or uppercase).

In the last example, you can see that in Python 3, if we try to write an integer with leading zeros, an error is thrown because this version already implemented a way to differentiate both numeral systems.

�� Tips: In Python 3, decimal numbers and zeros do accept leading zeros.

✅ Quick Tips: Octal Numeral System

I’m sure that you must be curious about this numeral system, so let’s analyze how 0000015 becomes 13 in Python 2. ��

1️⃣ Decimal System

This is the numeral system that we usually use in practice. It has base 10, which means that each digit is multiplied by 10 raised to a power to obtain the final result. The digits allowed in the decimal numeral system are 0–9.

For example:
1365 in the decimal numeral system is 1*(10³)+3*(10²)+6*(10¹)+5*(10⁰)
This is equivalent to 1000 + 300 + 60 + 5 = 1365.

See how we multiply each digit by 10 raised to a power starting from 0 and increasing by one for each place to the left?

2️⃣ Octal System

In contrast, numbers in the octal numeral system have base 8. This means that instead of multiplying by 10 raised to a power, we multiply by 8 raised to a power to transform the number to its equivalent number in the decimal system. The digits allowed in the octal numeral system are 0–7.

For example:
2536 in the octal numeral system is 2*(8³) +5*(8²)+3*(8¹)+6*(8⁰).
This is equivalent to 1024 + 320 + 24 + 6 = 1374 in the decimal system.

�� Note: Using a digit greater than 7 would cause an error.

�� Thank you!

I really hope that you liked my article. ❤️
I sincerely appreciate your claps and comments.��
Follow me on Medium | Twitter to find more articles like this. ��

Вывод числа с ведущими нолями

Нужно вывести последовательно эти числа в формате вида 000, 001, 002, . 100 . То есть идет заполнение справа-налево (не знаю как это называется).

Я понимаю, что можно условием все прогнать, но получается не так красиво.

А если числа не до 100, а до 1 000 000? Или вообще не известен диапазон? Есть ли иное решение?

Для Python >= 3.6, используйте f-string:

или метод format строки, который работает в любой версии:

Более подробно:

Желательно знать или вычислить максимальное количество позиций, которое потребуется для вывода числа max_width .

Если есть отрицательные числа, нужно учитывать, что знак будет занимать одну из позиций. Можно сделать так, чтобы знак выводился всегда.

Python zfill & rjust: Pad a String in Python

How to Pad a String in Python with zfill Cover Image

In this tutorial, you’ll learn how to use Python’s zfill method to pad a string with leadering zeroes. You’ll learn how the method works and how to zero pad a string and a number. You’ll also learn how to use the method in Pandas as well as how to use sign prefixes, such as + or -, in your padding. Finally, you’ll learn some alternatives to the Python zfill method, which give you different flexibility. These alternatives include the rjust function and using string formatting for padding and aligning your text.

The Quick Answer: Python zfill Pads a String with Leading Zeroes

Table of Contents

Python zfill: Overview

The Python zfill method is a string method that returns a copy of the string left filled with the ‘0’ character to make a character the length of a given width.

The method takes a single parameter, width . This parameter is used to assign the width of the desired string. Let’s take a look at the method:

The width parameter is mandatory. The method will raise a TypeError if no width is passed in. Similarly, the method will raise a TypeError if a floating point value is passed, rather than an integer value. Later in this tutorial, you’ll learn what happens when certain types of widths are passed.

In the next section, you’ll learn a brief overview of why you may want to pad a string in Python.

Why Zero Pad a String in Python

There are many reasons why you might want to zero pad a string in Python. For example, in many legacy finance applications, data systems will expect an input that is a certain length. In order to be able to insert data into these systems, you may need to zero pad your data.

Similarly, when importing data into Python, a key may be inferred as a number, thereby removing leading zeroes. This then creates challenges in terms of being able to merge datasets later on. By zero padding a number-like string allows you to safely reformat your data to be able to merge it across dataframes.

How to Use Python zfill to Pad a String in Python with Zeros

The Python zfill method is used to create a copy of a string with zeros padding the string to a particular width. Let’s try an example:

We can see that the method returned a string with the zeros padding the left side.
Remember, Python strings are immutable, meaning that they cannot be changed. We can verify this by applying the method and then pritning the original string:

If we wanted to “update” our string (remember, this won’t actually update the string, but rather create a new one), we need to re-assign it. Let’s see what this looks like:

How Do We Modify Our String?

We can see that we were able to successfully re-assign the string to itself with the .zfill() method applied.

Wondering what data type the .zfill() method returns? We can do this easily by using the type function. Let’s see what this returns:

Unsurprisingly, the zfill method returns a string data type.

What Happens If the Width is Shorter than the String?

Why don’t we take a look at what happens when the width we pass in is shorter than the original string? Let’s take a look at what happens:

If the width is either shorter or the same length as our original string, the method simply returns a copy of the original string.

How to Use Python zfill With Numbers

Because the zfill method is a string method, it can only be used with strings. There may be times when you want to pad a number with leading zeroes. Let’s see what happens when we try to apply the zfill method to an integer:

We can see that when we attempt to apply the method to an integer, that an AttributeError is raised.
In order to prevent this error, we need to first convert the integer into a string. We can do this using the str() function. Let’s see what this looks like:

It’s important to note that this is no longer an integer! It’s actually resulted in a string. This means that we can’t perform any operations you may normally associate with numbers, such as addition.

In the next section, you’ll learn how to use the zfill method in a Pandas dataframe to pad an entire dataframe column.

How to Zero Pad a Column in Pandas with zfill

There may be times when you want your Pandas dataframes’ values to be left-padded with zeros. Pandas actually implements the zfill method directly in a Pandas dataframe, meaning that we can apply the function in a vectorized format.
To see how this works, let’s first import a sample Pandas dataframe:

Let’s say we wanted to pad the values of ID column. We can simply apply the str.zfill() method to our dataframe column. Since these values are immutable, we need to be mindful to reassign the values to itself.

We can see how easy it is to pad a column with zeroes. Because the values in our column aren’t strings, we first need to convert them to strings using the .astype() method. If our column already was made of strings, we could skip this step.

## How to Zero Pad with Sign Prefixes in Python
The Python zfill method actually works really well when we want to assign sign prefixes, such as a + or – sign to a zero padded string. We simply need to include the sign prefix that we want and Python will take care of the rest.

Let’s take a look at what this looks like:

We can see that Python intelligently moved the sign prefix to the front of the string! This allows us to easily ensure that sign prefixes are respected.

One important thing to note here is that the sign prefix is included in the width of the string. Since we passed in a width of 5, we may have expected the returned copy to include three zeroes. However, because the full width is 5 including the sign, only two additional zeroes were included.

In the following two sections you’ll learn two alternatives to the zfill method!

Right Pad a String with Python rjust

There may be times that you want to pad a string but you don’t want to have it filled with zero values. In these cases, it can be helpful to use the rjust string method.

The rjust method is applied to a string and takes two parameters: (1) the width of the resulting string and (2) the character to use to pad the original string.

Let’s use a space to pad our string using the rjust method:

The benefit of this approach is that we can use any character to pad our strings with.

In the final section, you’ll learn how to use string formatting to pad a string.

Right Pad a String with Python String Formatting

In this final section, you’ll learn how to use Python string formatting to pad a string from the left.

Python makes this quite easy. Let’s see how we can use traditional string formatting to pad a string:

We use the :0 to ask Python to use 0s to pad our string and the >10 to indicate to pad from the left for a width of ten.

This approach is a bit more readable as it makes it immediately clear what string you’re hoping to pad.

Conclusion

In this tutorial, you learned how to use the Python zfill method to left-pad a string with zeroes. You also learned how to pad numbers with zeroes and how to pad a Pandas dataframe column. Finally, you learned some alternatives to the zfill method. These alternatives included the rjust method and Python string formatting.

Как дополнить строку ведущими нулями в Python 3

Я пытаюсь сделать length = 001 в Python 3, но всякий раз, когда я пытаюсь распечатать его, он обрезает значение без начальных нулей ( length = 1 ). Как я мог бы прекратить это делать, не откладывая length до строки перед ее печатью?

3 ответа

Используйте вспомогательный метод zfill() чтобы левый-pad использовать любую строку, целое число или float с нулями.

Когда применяется к значению, zfill() возвращает значение, оставшееся слева от нулей, когда длина начального строкового значения меньше, чем значение применяемой ширины, в противном случае начальное строковое значение as равно.

Целочисленные числа Python не имеют собственной длины или количества значащих цифр. Если вы хотите, чтобы они печатались определенным образом, вам нужно преобразовать их в строку. Есть несколько способов сделать это, чтобы вы могли указывать такие элементы, как пробельные символы и минимальные длины.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *