我有一串数字:
str = "4284902384902384093284"
output = []
我想将str
分成3位数的字符串,并将其存储在output
中。
有没有什么办法我可以使用split()
来做这件事?
我已经用two for loops
和slicing
做到了这一点。
我对split()
的问题是,您需要告诉Python分成什么部分,但是由于str
只是一个很长的数字列表(没有任何东西,甚至数字之间没有空格),我不确定如何应用split()
;
str.split(" ")
不工作,str.split("")
也不工作。我的想法是把它放到一个数组str = [str]
中,但是我不能完全使用split()。
So for the above input, I would like it to produce:
output = ["428","490","238",....]
发布于 2021-07-29 15:24:06
使用split
不能做到这一点,但是可以使用带有分片的列表表达式。
output = [string[i:i+3] for i in range(0, len(string), 3)]
对于您的示例字符串,它会生成:
['428', '490', '238', '490', '238', '409', '328', '4']
正如其他人提到的,您也可以使用正则表达式。这里有一种方法:
re.findall(r"\d{1,3}", string)
也会产生同样的结果。
此外,将字符串命名为str
也不是很好,因为这是内置string类的名称。
https://stackoverflow.com/questions/68578615
复制相似问题