[英]How to add digit in the beginning of string array in python?
eg I have this array例如我有这个数组
list=['123', '4', '56']
I want to add '0' in the beginning of list array that has 1 or 2 digit.我想在具有 1 位或 2 位数字的列表数组的开头添加“0”。 So the output will be:
所以 output 将是:
list=['123', '004', '056']
Use zfill
method:使用
zfill
方法:
In [1]: '1'.zfill(3)
Out[1]: '001'
In [2]: '12'.zfill(3)
Out[2]: '012'
Using a list comprehension, we can prepend the string '00'
to each number in the list, then retain the final 3 characters only:使用列表推导,我们可以在列表中的每个数字前面加上字符串
'00'
,然后只保留最后 3 个字符:
list = ['123', '4', '56']
output = [('00' + x)[-3:] for x in list]
print(output) # ['123', '004', '056']
As per How to pad zeroes to a string?根据如何将零填充到字符串? , you should use
str.zfill
: ,你应该使用
str.zfill
:
mylist = ['123', '4', '56']
output = [x.zfill(3) for x in mylist]
Alternatively, you could (though I don't know why you would) usestr.rjust
或者,你可以(虽然我不知道你为什么会)使用
str.rjust
output = [x.rjust(3, "0") for x in mylist]
or string formatting :或字符串格式:
output = [f"{x:0>3}" for x in mylist]
I'd say this would be a very easy to read example, but not the shortest.我想说这将是一个非常容易阅读的示例,但不是最短的。
Basically, we iterate through the lists elements, check if the length is 2 or 1. Based on that we will add the correct amount of '0'
基本上,我们遍历列表元素,检查长度是 2 还是 1。基于此,我们将添加正确数量的
'0'
lst=['123', '4', '56']
new = []
for numString in lst:
if len(numString) == 2:
new.append('0'*1+numString)
elif len(numString) == 1:
new.append('0'*2+numString)
else:
new.append(numString)
print(new)
Also I kind of had to include it (list comprehension).But this is barely readable,so I gave the above example.我也不得不包括它(列表理解)。但这几乎不可读,所以我给出了上面的例子。 Look here for list comprehension with
if, elif, else
在此处查找带有
if, elif, else
的列表理解
lst=['123', '4', '56']
new = ['0'*1+numString if len(numString) == 2 else '0'*2+numString if len(numString) == 1 else numString for numString in lst]
print(new)
output output
['123', '004', '056']
trying into integer and add preceding zero/s then convert into a string and replace the element in the same position and the same list尝试进入 integer 并添加前面的零/秒然后转换为字符串并替换相同 position 和相同列表中的元素
list=["3","45","111"] n=len(list) for i in range(0,n): list[i] = str(f"{int(list[i]):03}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.