Format python ведущие нули

Display number with leading zeros [duplicate]

Basically % is like printf or sprintf (see docs).

For Python 3.+, the same behavior can also be achieved with format :

number = 1 print("".format(number)) 

For Python 3.6+ the same behavior can be achieved with f-strings:

x = «%02d.txt» % i raises TypeError (cannot concatenate ‘str’ and ‘int’ objects), but x = «%02d.txt» % (i,) does not. Interesting. I wonder where is that documented

@theta In 2.7.6, I don’t get an error. Maybe this was a bug in a specific version of Python that they’ve since fixed?

Maybe. In 2.7.6 there is no exception if format value isn’t tuple (at least for this example). Looking at the date of my comment I guess I was running 2.7.3 back then, and at that time I didn’t know that putting single variable in a tuple gets you on a safe side while using % string formater.

To elaborate, the docs explain this here: «When no explicit alignment is given, preceding the width field by a zero (‘0’) character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of ‘0’ with an alignment type of ‘=’.»

print(str(1).zfill(2)) print(str(10).zfill(2)) print(str(100).zfill(2)) 

I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable. e.g. x = str(datetime.date.today().month).zfill(2) will return x as ’02’ for the month of feb.

This should be the correct answer, since the «<1:02d>» cannot have variables in place of 2 (like if you are creating a dynamic function).

@JoshuaVarghese It can have variables: «<0:0>» . Pass any number of zeros you want as the second argument.

In Python 2.6+ and 3.0+, you would use the format() string method:

for i in (1, 10, 100): print(''.format(num=i)) 

or using the built-in (for a single number):

See the PEP-3101 documentation for the new formatting functions.

Works in Python 2.7.5 as well. You can also use ‘<:02d>‘.format(1) if you don’t want to use named arguments.

Works fine in 2.7.2, with a floating point «<0:04.0f>«.format(1.1) gives 0001 (:04 = at least 4 characters, in this case leading 0’s, .0f = floating point with no decimals). I am aware of the % formatting but wanted to modify an existing .format statement without rewriting the whole thing. Thanks!

print(''.format(1)) print(''.format(10)) print(''.format(100)) 

This way let you repeat the argument several times within the string: One zero:<0:02>, two zeros: , ninezeros: ‘.format(6)

In Python >= 3.6, you can do this succinctly with the new f-strings that were introduced by using:

which prints the variable with name val with a fill value of 0 and a width of 2 .

For your specific example you can do this nicely in a loop:

a, b, c = 1, 10, 100 for val in [a, b, c]: print(f'') 

For more information on f-strings, take a look at PEP 498 where they were introduced.

x = [1, 10, 100] for i in x: print '%02d' % i 

The documentation example sucks. They throw mapping in with the leading zero sample, so it’s hard to know which is which unless you already know how it works. Thats what brought me here, actually.

The Pythonic way to do this:

str(number).rjust(string_width, fill_char) 

This way, the original string is returned unchanged if its length is greater than string_width. Example:

a = [1, 10, 100] for num in a: print str(num).rjust(2, '0') 

This would be the Python way, although I would include the parameter for clarity — «<0:0>2>».format(number) , if someone will wants nLeadingZeros they should note they can also do: «<0:0>>».format(number, nLeadingZeros + 1)

You can do this with f strings.

import numpy as np print(f'8>') 

This will print constant length of 8, and pad the rest with leading 0 .

00000001 00000124 00013566 

Basically zfill takes the number of leading zeros you want to add, so it’s easy to take the biggest number, turn it into a string and get the length, like this:

Python 3.6.5 (default, May 11 2018, 04:00:52) [GCC 8.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> total = 100 >>> print(str(1).zfill(len(str(total)))) 001 >>> total = 1000 >>> print(str(1).zfill(len(str(total)))) 0001 >>> total = 10000 >>> print(str(1).zfill(len(str(total)))) 00001 >>>
width = 5 num = 3 formatted = (width - len(str(num))) * "0" + str(num) print formatted 

which will return a string.

Its built into python with string formatting

This old question doesn’t need any more answers. Your answer is also a duplicate of the accepted answer without any additional information.

import math '00'[math.ceil(math.log(i, 10)):] + str(i) 

All of these create the string «01»:

>python -m timeit "''.format(1)" 1000000 loops, best of 5: 357 nsec per loop >python -m timeit "'d>'.format(1,2)" 500000 loops, best of 5: 607 nsec per loop >python -m timeit "f''" 1000000 loops, best of 5: 281 nsec per loop >python -m timeit "f'd>'" 500000 loops, best of 5: 423 nsec per loop >python -m timeit "str(1).zfill(2)" 1000000 loops, best of 5: 271 nsec per loop >python Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32 

This would be the Python way, although I would include the parameter for clarity — «2>».format(number), if someone will wants nLeadingZeros they should note they can also do:»>».format(number, nLeadingZeros + 1)

If dealing with numbers that are either one or two digits:

‘0’+str(number)[-2:] or ‘0’.format(number)[-2:]

Linked

Hot Network Questions

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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

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

for i in range(101): x = i if i < 10: x = '00' + str(i) elif i >= 10 and i  

5 ответов 5

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

>>> x = 10 >>> print(f'') ^ желаемая длина строки 00010 

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

''.format(10) # '00010' ^ желаемая длина строки 

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

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

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

Для дробных чисел нужно учитывать позицию для точки (запятой).

max_width = 5 print(f'>') # 00010 - вывод с добавлением нолей print(f'>') # -0010 - минус забирает одну позицию print(f'>') # -10000 - если число слишком большое, # строка будет длиннее, чем max_width print(f'>') # +0010 - обязательный вывод знака print(f'>') # 010.5 - точка забирает одну позицию print(f'>') # 10 - можно заполнять пробелами 

Подробнее про возможности форматирования можно почитать в документации:

Источник

Format a number containing a decimal point with leading zeroes

considers all the digits and even the decimal point. Is there a function in python that considers only the whole part? I only need to format simple numbers with no more than five decimal places. Also, using %5f seems to consider trailing instead of leading zeros.

6 Answers 6

Is that what you look for?

So according to your comment, I can come up with this one (although not as elegant anymore):

>>> fmt = lambda x : "%04d" % x + str(x%1)[1:] >>> fmt(3.1) 0003.1 >>> fmt(3.158) 0003.158 

I like the new style of formatting.

loop = 2 pause = 2 print 'Begin Loop , Seconds Pause'.format(loop, pause) >>>Begin Loop 2, 0002.1 Seconds Pause 
  • 1 is the place holder for variable pause
  • 0 indicates to pad with leading zeros
  • 6 total number of characters including the decimal point
  • 2 the precision
  • f converts integers to floats

This will have total 7 characters including 3 decimal points, ie. "012.340"

Starting with a string as your example does, you could write a small function such as this to do what you want:

def zpad(val, n): bits = val.split('.') return "%s.%s" % (bits[0].zfill(n), bits[1]) >>> zpad('3.3', 5) '00003.3' 

That's exactly what I didn't want to do, But if there's no built-in function, I guess it will work. Thanks.

@3ee3 Try this on '3' . If you want a version that works on int s as well as float s, add a line bits[0] = bits[0].zfill(n) before the return , and change the return to return bits = '.'.join(bits) . `

What about -3.3 ? Doesn't produce expected results!! Add a condition if val.count('-')>0: n=n+1 then it will work for that as well

With Python 3.6+ you can use the fstring method:

This method will eliminate the fractional component (consider only the whole part) and return up to 5 digits. Two caveats: First, if the whole part is larger than 5 digits, the most significant digits beyond 5 will be removed. Second, if the fractional component is greater than 0.5, the function will round up.

Источник

Best way to format integer as string with leading zeros? [duplicate]

I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:

function add_nulls($int, $cnt=2)

10 Answers 10

You can use the zfill() method to pad a string with zeros:

The way 004 is parsed by the compiler, and then represented in memory, is exactly the same as 4 . The only time a difference is visible is in the .py source code. If you need to store information like "format this number with leading zeros until the hundreds place", integers alone cannot provide that - you need to use alternate data structures (string work well in this case)

Need to say that this is not correct. The fact that 004 == 4 is kinda fortune. The way interpreter (python is not compiled) parses ints is different for ints starting with a leading 0 . If a number starts with 0 then it is considered as 8-nary number. So yeah, 004 == 4 , but 040 != 40 because 040 = 4 * 8 + 0 = 32 .

To clarify a couple of things: 1. That is true only for parsing of integer literals, not for conversion of strings to ints - eg. if you do a = 010 then the value of a will be 8 but if you do a = int("010") the value of a will be 10. 2. Only Python 2 behaves this way - in python 3, a = 010 would give a syntax error. Octals in python 3 start with 0o, eg. 0o10 (presumably to avoid this exact confusion).

The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.

To output a string of length 5:

. in Python 3.5 and above: f-strings.

i = random.randint(0, 99999) print(f'') 

Search for f-strings here for more details.

@Zelphir you can dynamically create the formatting string, [('>').format(len(my_list)).format(k) for k in my_list]

I've chosen to concat the format string instead, inserting the length of a list for example. Are there any advantages of your way of doing it?

There is no need to use str.format() when all the template contains is one <. >placeholder. Avoid parsing the template and use the format() function instead: format(i, '05d')

@Mark There is no need to use nested/stacked formats. The number of digits can be variable: [('<0:0d>').format(k, len(my_list)) for k in my_list] --- with f-string: [f'd>' for k in my_list] --- It is weird that the number of digits is determined by the number of items. You probably want to prepare max_digits and use [f'd>' for k in my_list]

Python 3.6 f-strings allows us to add leading zeros easily:

number = 5 print(f' now we have leading zeros in ') 

Have a look at this good post about this feature.

You most likely just need to format your integer:

This is not permanent - in fact you cannot add zeroes permanently to the from of an int - that would then be interpreted as an octal value.

@Matthew Schnickel: I think the OP wants to know a method to compute the number of zeros he needs. Formatting handles that fine. And int(x, 10) handles the leading zeros.

add_nulls = lambda number, zero_count : "d>".format(number, zero_count) >>>add_nulls(2,3) '002' 

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

 # if we want to pad 22 with zeros in front, to be 5 digits in length: str_output = '5>'.format(22) print(str_output) # >>> 00022 # 5> meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5 # another example for comparision str_output = ''.format(11) print(str_output) # >>> 11## # to put it in a less hard-coded format: int_inputArg = 22 int_desiredLength = 5 str_output = '>'.format(str_0=int_inputArg, str_1=int_desiredLength) print(str_output) # >>> 00022 

Источник

Читайте также:  Корреляционный анализ данных python
Оцените статью