簡體   English   中英

如何將零添加到用戶輸入數組的所有數字並將所有數字轉換為相同的數字?

[英]how can i add zeros to all the numbers of the user entered array and convert all numbers to the same digits?

我不能使用像 zfill 這樣的任何功能

n = int(input('n: '))
arr = [None]*n
for p in range (n):
    arr[p] = int(input())

例如,如果用戶輸入 62,32,654,32649,我希望他們轉換為 00062,00032,00654,32649

您可以使用格式字符串:

values = [62,32,654,32649]
print(*(f"{n:05}" for n in values))

00062 00032 00654 32649

這適用於將數據打印或操作為字符串。 當您將它們int()時,數字的內部表示中沒有前導零的概念。

要填充到最大數字,您可以使用嵌套格式字符串:

size = max(map(len,map(str,values)))
print(*(f"{n:0{size}}" for n in values))

使用以下代碼:

n = input('n: ')
l = [x.zfill(5) for x in n.split(',')]
z = ','.join(l)
print(z)

輸入:

62,32,654,32649

output:

00062,00032,00654,32649

我認為您應該查看字符串的.format()方法。 下面的頁面代碼片段中,#8 可能會有所幫助。 在你的情況下,我會建議

n = int(input('n: '))
arr = [None]*n
for p in range (n):
    arr[p] = "{:05d}".format(int(input()))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM