input = ["AB0","A","BBBB"]
output = ["000","0","0000"]
有沒有像.replace("", "")
功能,可把任何輸入,並給予零的字符串具有相同的字符數?改變字符串的所有值到一定值
input = ["AB0","A","BBBB"]
output = ["000","0","0000"]
有沒有像.replace("", "")
功能,可把任何輸入,並給予零的字符串具有相同的字符數?改變字符串的所有值到一定值
這將工作:
input = ["AB0","A","BBBB"]
output = ["0"*len(x) for x in input]
或相同:
input = ["AB0","A","BBBB"]
output = []
for x in input:
output.append("0"*len(x))
沒有這樣的內置功能,但你可以很容易地編寫一個list comprehension:
>>> input = ["AB0","A","BBBB"]
>>>
>>> ["0" * len(item) for item in input]
['000', '0', '0000']
您可以使用python're'模塊,如下所示:
import re
input = ["AB0","A","BBBB"]
output = []
for value in input:
str = re.sub(".","0",value)
output.append(str)
print output
map(lambda x:"0"*len(x),["AB0","A","BBB"])
另一種方式來做到這一點(主要是爲了好玩):
>>> input = ["AB0", "A", "BBBB"]
>>> zeros = ''.zfill
>>> [zeros(len(s)) for s in input]
['000', '0', '0000']
請注意,這僅適用於與0
填充。如果你想填充不同的字符,那麼這種方法將無法工作。
你可以使用ljsut
或rjust
來填充不同的字符...
>>> input = ["AB0", "A", "BBBB"]
>>> pad = ''.ljust
>>> [pad(len(s), '1') for s in input]
['111', '1', '1111']
然而,大多數的這些都是真的只是巧妙的方法來做到這一點。他們是不是更快:
>>> timeit.timeit("[pad(len(s), '1') for s in input]", 'from __main__ import pad, input')
1.3355789184570312
>>> timeit.timeit("['1' * len(s) for s in input]", 'from __main__ import pad, input')
0.8812301158905029
>>> zeros = ''.zfill
>>> timeit.timeit("[zeros(len(s)) for s in input]", 'from __main__ import zeros, input')
1.110482931137085
不過,根據您的特定偏好/背景,你可能會發現一個更清晰的方式比另一種明白(這就是值得的東西)...
FWIW,我的第一次本能是使用 Selcuk's answer中提出的乘法方法,所以這可能是我認爲最容易閱讀和理解的...
對於s [len(s),「h」)在輸入]'?例如 – TheClonerx
@TheClonerx - 是的,我也在想這個。既然你提出了這個問題,我正在考慮這個問題,我想我會加上它。 – mgilson