Jak wstawić zera do łańcucha?
Co to jest Pythoniczny sposób na umieszczenie łańcucha liczbowego z zerami w lewo, tzn. że łańcuch liczbowy ma określoną długość?
17 answers
Ciągi:
>>> n = '4'
>>> print(n.zfill(3))
004
I dla liczb:
>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n)) # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n)) # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n)) # python >= 2.7 + python3
004
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-21 13:27:01
Wystarczy użyć metody rjust obiektu string.
Ten przykład utworzy ciąg znaków o długości 10 znaków, wypełniając w razie potrzeby.
>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-02 16:05:48
Oprócz zfill
, możesz użyć ogólnego formatowania ciągu znaków:
print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))
Dokumentacja dla formatowania łańcuchów i F-ciągów .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-16 19:03:50
Dla Pythona 3.6 + używanie ciągów f:
>>> i = 1
>>> f"{i:0>2}" # Works for both numbers and strings.
'01'
>>> f"{i:02}" # Works only for numbers.
'01'
Dla Pythona 2 do Pythona 3.5:
>>> "{:0>2}".format("1") # Works for both numbers and strings.
'01'
>>> "{:02}".format(1) # Works only for numbers.
'01'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-15 23:18:29
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'
Jeśli chcesz odwrotnie:
>>> '99'.ljust(5,'0')
'99000'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-10 23:19:37
str(n).zfill(width)
będzie współpracować z string
s, int
s, float
s... i jest Python 2. x i 3.x kompatybilny:
>>> n = 3
>>> str(n).zfill(5)
'00003'
>>> n = '3'
>>> str(n).zfill(5)
'00003'
>>> n = '3.0'
>>> str(n).zfill(5)
'003.0'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-01 04:40:02
Jaki jest najbardziej pythoniczny sposób na umieszczenie ciągu liczbowego z zerami w lewo, tzn., że ciąg liczbowy ma określoną długość?
str.zfill
ma to na celu:
>>> '1'.zfill(4)
'0001'
Zauważ, że jest przeznaczony do obsługi ciągów liczbowych zgodnie z wymaganiami i przenosi +
lub -
na początek łańcucha:
>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
Oto pomoc na str.zfill
:
>>> help(str.zfill)
Help on method_descriptor:
zfill(...)
S.zfill(width) -> str
Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
Wydajność
Jest to również najbardziej wykonawca metod alternatywnych:
>>> min(timeit.repeat(lambda: '1'.zfill(4)))
0.18824880896136165
>>> min(timeit.repeat(lambda: '1'.rjust(4, '0')))
0.2104538488201797
>>> min(timeit.repeat(lambda: f'{1:04}'))
0.32585487607866526
>>> min(timeit.repeat(lambda: '{:04}'.format(1)))
0.34988890308886766
Aby najlepiej porównać jabłka do jabłek dla metody %
(zauważ, że jest ona w rzeczywistości wolniejsza), która w przeciwnym razie obliczy wstępnie:
>>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
0.19728074967861176
>>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
0.2347015216946602
Wdrożenie
Trochę poszperałem, znalazłem implementację metody zfill
W Objects/stringlib/transmogrify.h
:
static PyObject *
stringlib_zfill(PyObject *self, PyObject *args)
{
Py_ssize_t fill;
PyObject *s;
char *p;
Py_ssize_t width;
if (!PyArg_ParseTuple(args, "n:zfill", &width))
return NULL;
if (STRINGLIB_LEN(self) >= width) {
return return_self(self);
}
fill = width - STRINGLIB_LEN(self);
s = pad(self, fill, 0, '0');
if (s == NULL)
return NULL;
p = STRINGLIB_STR(s);
if (p[fill] == '+' || p[fill] == '-') {
/* move sign to beginning of string */
p[0] = p[fill];
p[fill] = '0';
}
return s;
}
Przejdźmy przez ten kod C.
Najpierw parsuje argument pozycyjnie, co oznacza, że nie pozwala na argumenty słów kluczowych:
>>> '1'.zfill(width=4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: zfill() takes no keyword arguments
Wtedy sprawdza, czy ma taką samą lub dłuższą długość, w takim przypadku zwraca ciąg znaków.
>>> '1'.zfill(0)
'1'
zfill
wywołania pad
(ta pad
funkcja jest również wywoływana przez ljust
, rjust
, i center
również). To w zasadzie kopiuje zawartość do nowego ciągu i wypełnia wyściółkę.
static inline PyObject *
pad(PyObject *self, Py_ssize_t left, Py_ssize_t right, char fill)
{
PyObject *u;
if (left < 0)
left = 0;
if (right < 0)
right = 0;
if (left == 0 && right == 0) {
return return_self(self);
}
u = STRINGLIB_NEW(NULL, left + STRINGLIB_LEN(self) + right);
if (u) {
if (left)
memset(STRINGLIB_STR(u), fill, left);
memcpy(STRINGLIB_STR(u) + left,
STRINGLIB_STR(self),
STRINGLIB_LEN(self));
if (right)
memset(STRINGLIB_STR(u) + left + STRINGLIB_LEN(self),
fill, right);
}
return u;
}
Po wywołaniu pad
, zfill
przesuwa dowolny pierwotnie poprzedzający +
lub -
na początek łańcucha.
Zauważ, że dla oryginalnego ciągu rzeczywiście być liczbowe nie jest "required": {]}
>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-24 14:21:03
Dla tych, którzy przyszli tutaj, aby zrozumieć, a nie tylko szybką odpowiedź. Robię to specjalnie dla strun czasu:
hour = 4
minute = 3
"{:0>2}:{:0>2}".format(hour,minute)
# prints 04:03
"{:0>3}:{:0>5}".format(hour,minute)
# prints '004:00003'
"{:0<3}:{:0<5}".format(hour,minute)
# prints '400:30000'
"{:$<3}:{:#<5}".format(hour,minute)
# prints '4$$:3####'
Symbole"0" co zastąpić "2", domyślnie jest pusta spacja
">" symbole wyrównują wszystkie znaki 2 " 0 " po lewej stronie łańcucha
": "symbole formula_spec
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-30 16:09:58
Podczas używania Pythona >= 3.6
, najczystszym sposobem jest użycie f-stringów z formatowaniem łańcuchów :
>>> s = f"{1:08}" # inline with int
>>> s
'00000001'
>>> s = f"{'1':0>8}" # inline with str
>>> s
'00000001'
>>> n = 1
>>> s = f"{n:08}" # int variable
>>> s
'00000001'
>>> c = "1"
>>> s = f"{c:0>8}" # str variable
>>> s
'00000001'
Wolałbym formatowanie za pomocą int
, ponieważ tylko wtedy znak jest obsługiwany poprawnie:
>>> f"{-1:08}"
'-0000001'
>>> f"{1:+08}"
'+0000001'
>>> f"{'-1':0>8}"
'000000-1'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-19 18:45:28
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005
Zobacz dokumentację wydruku dla wszystkich ekscytujących szczegółów!
Aktualizacja dla Pythona 3.x (7,5 lat później)
Ostatnia linijka powinna brzmieć:
print("%0*d" % (width, x))
Tzn. print()
jest teraz funkcją, a nie deklaracją. Zauważ, że nadal wolę styl Old School printf()
, ponieważ, imnsho, czyta się lepiej, i dlatego, że używam tej notacji od stycznia 1980. Coś ... stare psy .. coś, coś ... nowe sztuczki.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-10 22:03:54
Dodaję jak używać int z długości łańcucha w ciągu f, ponieważ nie wygląda na to, że jest zakryty:
>>> pad_number = len("this_string")
11
>>> s = f"{1:0{pad_number}}" }
>>> s
'00000000001'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-25 15:08:26
Dla kodów pocztowych zapisanych jako liczby całkowite:
>>> a = 6340
>>> b = 90210
>>> print '%05d' % a
06340
>>> print '%05d' % b
90210
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-14 09:17:11
Szybkie porównanie czasu:
setup = '''
from random import randint
def test_1():
num = randint(0,1000000)
return str(num).zfill(7)
def test_2():
num = randint(0,1000000)
return format(num, '07')
def test_3():
num = randint(0,1000000)
return '{0:07d}'.format(num)
def test_4():
num = randint(0,1000000)
return format(num, '07d')
def test_5():
num = randint(0,1000000)
return '{:07d}'.format(num)
def test_6():
num = randint(0,1000000)
return '{x:07d}'.format(x=num)
def test_7():
num = randint(0,1000000)
return str(num).rjust(7, '0')
'''
import timeit
print timeit.Timer("test_1()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_2()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_3()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_4()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_5()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_6()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_7()", setup=setup).repeat(3, 900000)
> [2.281613943830961, 2.2719342631547077, 2.261691106209631]
> [2.311480238815406, 2.318420542148333, 2.3552384305184493]
> [2.3824197456864304, 2.3457239951596485, 2.3353268829498646]
> [2.312442972404032, 2.318053102249902, 2.3054072168069872]
> [2.3482314132374853, 2.3403386400002475, 2.330108825844775]
> [2.424549090688892, 2.4346475296851438, 2.429691196530058]
> [2.3259756401716487, 2.333549212826732, 2.32049893822186]
Zrobiłem różne testy różnych powtórzeń. Różnice nie są ogromne, ale we wszystkich testach rozwiązanie zfill
było najszybsze.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-28 10:58:09
Innym podejściem byłoby użycie rozumienia listy z sprawdzaniem stanu długości. Poniżej znajduje się demonstracja:
# input list of strings that we want to prepend zeros
In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]
# prepend zeros to make each string to length 8, if length of string is less than 8
In [83]: ["0"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]
Out[83]: ['00101010', '10101010', '00011110', '00000000']
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-05 01:25:07
Its ok too:
h = 2
m = 7
s = 3
print("%02d:%02d:%02d" % (h, m, s))
Więc wyjście będzie: "02:07:03"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-30 07:38:40
Stworzyłem funkcję:
def PadNumber(number, n_pad, add_prefix=None):
number_str = str(number)
paded_number = number_str.zfill(n_pad)
if add_prefix:
paded_number = add_prefix+paded_number
print(paded_number)
PadNumber(99, 4)
PadNumber(1011, 8, "b'")
PadNumber('7BEF', 6, "#")
Wyjście:
0099
b'00001011
#007BEF
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-10 05:05:37
Można również powtórzyć "0", poprzedzić go do str(n)
i uzyskać najbardziej po prawej stronie plaster szerokości. Szybki i brudny wyraz twarzy.
def pad_left(n, width, pad="0"):
return ((pad * width) + str(n))[-width:]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-21 10:51:49