[英]How to split a string into pairs of equal length with 0 in the empty positions in python?
我有一个字符串,例如“6PH57VP3+PR”,我需要拆分它以获得这些字符串:“6P00000000”、“00H5000000”、“00007V0000”、“000000P300”、“00000000PR”。 有没有一个简单的 python function 可以做到这一点?
我不认为有一个简单的 function 可以做到这一点,但很容易做到:
def f(s):
res = []
#before +
for i in range(0,len(s)-3,2):
a = ['0']*len(s)
a[i:i+2] = s[i:i+2]
res.append("".join(a))
# the last 2 after +
a = ['0']*len(s)
a[-2:] = s[-2:]
res.append("".join(a))
return res
assert f('6PH57VP3+PR') == ['6P000000000', '00H50000000', '00007V00000', '000000P3000', '000000000PR']
假设您总是想删除+
并且字符串的长度始终相同,您可以使用列表推导。
location_code = '6PH57VP3+PR'
location_code_list = ['0'*s+location_code.replace('+','')[s:s+2]+'0'*(8-s)
for s in range(0, 10, 2)]
print(location_code_list)
""" output
['6P00000000', '00H5000000', '00007V0000', '000000P300', '00000000PR']
"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.