programing

끈에 0을 어떻게 채워요?

minecode 2022. 12. 10. 11:03
반응형

끈에 0을 어떻게 채워요?

숫자 문자열을 왼쪽으로 0으로 채우려면 어떻게 해야 하나요? 문자열의 길이가 특정되도록 하려면?

문자열을 채우려면:

>>> n = '4'
>>> print(n.zfill(3))
004

번호를 채우려면:

>>> 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

문자열 포맷 매뉴얼

문자열 객체의 메서드를 사용합니다.

다음 예제에서는 필요에 따라 패딩하여 10자 길이의 문자열을 만듭니다.

>>> s = 'test'
>>> s.rjust(10, '0')
>>> '000000test'

게다가.zfill일반적인 문자열 형식을 사용할 수 있습니다.

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'))

문자열 포맷f-string관한 문서.

f-string을 사용하는 Python 3.6+의 경우:

>>> i = 1
>>> f"{i:0>2}"  # Works for both numbers and strings.
'01'
>>> f"{i:02}"  # Works only for numbers.
'01'

Python 2에서 Python 3.5로의 경우:

>>> "{:0>2}".format("1")  # Works for both numbers and strings.
'01'
>>> "{:02}".format(1)  # Works only for numbers.
'01'
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'

그 반대일 경우:

>>> '99'.ljust(5,'0')
'99000'

str(n).zfill(width)사용할 수 있다strings,ints,floats... 및 Python 2.x와 3.x의 호환성이 있습니까?

>>> n = 3
>>> str(n).zfill(5)
'00003'
>>> n = '3'
>>> str(n).zfill(5)
'00003'
>>> n = '3.0'
>>> str(n).zfill(5)
'003.0'

숫자 문자열에 0을 왼쪽으로 패딩하는 가장 비토닉한 방법은 무엇입니까? 즉, 숫자 문자열의 길이가 특정되도록 합니다.

str.zfill 에서는, 다음과 같이 하는 것을 목적으로 하고 있습니다.

>>> '1'.zfill(4)
'0001'

이는 특히 요구에 따라 숫자 문자열을 처리하는 것을 목적으로 하며,는+또는-문자열의 선두까지:

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'

에 대한 도움입니다.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.

성능

이 방법은 대체 방법 중 가장 성능이 우수합니다.

>>> 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

에 대해 사과와 사과를 가장 잘 비교하는 방법%method(실제로 속도가 느리다는 점에 유의하십시오)를 지정하면 다음과 같이 사전 설정됩니다.

>>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
0.19728074967861176
>>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
0.2347015216946602

실행

좀 더 파헤쳐보니, 그 실행이zfill의 메서드:

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;
}

이 C코드를 살펴봅시다.

먼저 인수를 위치적으로 해석합니다.즉, 키워드 인수는 사용할 수 없습니다.

>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: zfill() takes no keyword arguments

그런 다음 길이가 같은지 또는 더 긴지 확인하고 이 경우 문자열을 반환합니다.

>>> '1'.zfill(0)
'1'

zfillpad(이것pad함수는 또한 에 의해 호출됩니다.ljust,rjust,그리고.center(도 마찬가지입니다).기본적으로 내용을 새 문자열로 복사하고 패딩을 채웁니다.

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;
}

통화 후pad,zfill원래 이전을 이동하다+또는-스트링의 선두까지를 표시합니다.

원래 문자열이 실제로 숫자일 필요는 없습니다.

>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'

여기 오신 분들께는 빠른 답변이 아니라 이해해주셨으면 좋겠습니다.특히 시간 문자열에 대해 다음을 수행합니다.

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####'

"0"은 "2" 패딩 문자로 대체할 항목을 나타냅니다. 기본값은 공백입니다.

">" 기호는 문자열 왼쪽에 2개의 "0" 문자를 모두 지정합니다.

":"는 format_spec을 나타냅니다.

Python 사용 시>= 3.6가장 깨끗한 방법은 문자열 포맷으로 f-module사용하는 것입니다.

>>> 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'

포맷을 더 선호합니다.int가 올바르게 기호는 올바르게 처리됩니다.

>>> f"{-1:08}"
'-0000001'

>>> f"{1:+08}"
'+0000001'

>>> f"{'-1':0>8}"
'000000-1'

숫자의 경우:

i = 12
print(f"{i:05d}")

산출량

00012
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005

상세한 것에 대하여는, 인쇄 문서를 참조해 주세요.

Python 3.x 업데이트 (7.5년 후)

이제 마지막 줄은 다음과 같습니다.

print("%0*d" % (width, x))

ㅇㅇ.print()이제 문장이 아닌 함수입니다.는 여전히 스쿨을 합니다.printf()왜냐하면 IMNSHO가 더 잘 읽히기 때문이고, 음, 1980년 1월부터 그 표기법을 써왔거든요. 개들속임수야새로운 속임수

f-string 내의 문자열 길이에서 int를 사용하는 방법은 커버되어 있지 않기 때문에 추가합니다.

>>> pad_number = len("this_string")
11
>>> s = f"{1:0{pad_number}}" }
>>> s
'00000000001'

정수로 저장된 우편 번호의 경우:

>>> a = 6340
>>> b = 90210
>>> print '%05d' % a
06340
>>> print '%05d' % b
90210

빠른 타이밍 비교:

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]

여러 번 반복해서 여러 가지 테스트를 해봤습니다., ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」zfill솔루션이 가장 빠릅니다.

그것도 괜찮아요.

 h = 2
 m = 7
 s = 3
 print("%02d:%02d:%02d" % (h, m, s))

출력은 "02:07:03"이 됩니다.

또 다른 접근법은 길이 체크 조건과 함께 목록 이해를 사용하는 것이다.다음은 데모를 보여드리겠습니다.

# 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']

함수를 만들었습니다.

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, "#")

출력은 다음과 같습니다.

0099
b'00001011
#007BEF

정수를 채우면서 유효 수치를 동시에 제한하는 경우(f 문자열 사용):

a = 4.432
>> 4.432
a = f'{a:04.1f}'
>> '04.4'

f'{a:04.1f}'이것은 소수점/(소수점) 1로 변환되며, 총 4글자가 될 때까지 숫자를 왼쪽 패드로 표시합니다.

'0을 반복하고 0' 앞에 '0'을.str(n)가장 오른쪽 폭의 슬라이스를 얻을 수 있습니다.빠르고 지저분한 작은 표정.

def pad_left(n, width, pad="0"):
    return ((pad * width) + str(n))[-width:]

언급URL : https://stackoverflow.com/questions/339007/how-do-i-pad-a-string-with-zeroes

반응형