【每日一题0618】 python 字符串格式化(不使用zfill方法)

请输出1-1000的数字如下格式:
0001
0002
0003
...
1000

题解1:利用%格式化占位符

def parse_1(n:int):
    return ('%04d' % n)
    
assert '0008' == parse_1(8)
assert '0088' == parse_1(88)
assert '0888' == parse_1(888)
assert '1000' == parse_1(1000)

题解2:倒着切片

def parse_2(n:int):
    return ('0000'+str(n))[-4:]

assert '0008' == parse_2(8)
assert '0088' == parse_2(88)
assert '0888' == parse_3(888)
assert '1000' == parse_3(1000)

题解3:利用双端队列,后进前出。

from queue import deque

def parse_3(n:int):
    dq = deque(['0', '0', '0', '0'])
    
    for i in list(str(n)):
        dq.append(i)
        dq.popleft()
    return ''.join(list(dq))

assert '0008' == parse_3(8)
assert '0088' == parse_3(88)
assert '0888' == parse_3(888)
assert '1000' == parse_3(1000)

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

1 个赞
print("%04d"%num)

def parse_1(n:int):

return ("{:0>4}".format(n))

assert ‘0008’ == parse_1(8)
assert ‘0088’ == parse_1(88)
assert ‘0888’ == parse_1(888)
assert ‘1000’ == parse_1(1000)

利用rjust补位
def parse(n:int):
    return str(n).rjust(4,'0')
def parse_1(n: int):
    return '%04d' % n


def parse_2(n: int):
    return ("0000" + str(n))[-4:]


print(parse_1(1))
print(parse_1(1))
def parse(n: int):
    from collections import deque
    dq = deque(['0','0','0','0'],maxlen=4)
    for i in str(n):
        dq.append(i)
    return ''.join(dq)
#字符串格式化
def format_number(n:int):
	print("{:0>4d}".format(n))
format_number(1000)

##字符拼接
def format_number1(m:int):
	n=0
	while n<4:
		res=n*"0"+str(m)
		if len(res)==4:
			return res
		else:
			n+=1
format_number1(900)
def parse(n):
    # return ('%04d' %n)
    return "{:>04}".format(n)
def parse_1(n: int):
    return (str(n)[::-1]+'0'*(4-len(str(n))))[::-1]

assert '0008' == parse_1(8)
assert '0088' == parse_1(88)
assert '0888' == parse_1(888)
assert '1000' == parse_1(1000)