‘ 7w876543217w'怎么拆分成[7w,87,65,43,21,7w]
list['7w876543217w']貌似不行
1
Cooky 2017-09-11 18:35:33 +08:00 via Android
[ list[i,I+2] for i in range(len(list)) ]
|
4
qlbr 2017-09-11 18:37:46 +08:00 1
>>> import re
>>> string='7w876543217w' >>> re.findall('.{2}',string) ['7w', '87', '65', '43', '21', '7w'] |
6
nauynah 2017-09-11 20:10:54 +08:00 via iPhone 2
>>> [str[i: i+2] for i in range(0, 10, 2)]
|
7
acheapskate 2017-09-11 20:11:19 +08:00 1
s = '7w876543217w'
l = [m + n for m,n in zip(s[0::2],s[1::2])] |
8
acheapskate 2017-09-11 20:19:32 +08:00
@nauynah range(0, 11, 2) ,不然截取不到最后 2 个字符 。感觉用 range 分隔还是最明晰方便的
|
9
nauynah 2017-09-11 20:35:59 +08:00
@acheapskate 是的,我把字符串长度看成 10 了
|
10
40huo 2017-09-11 21:30:47 +08:00 1
[string[x : x + width] for x in range(0, len(string), width)]
|
11
yucongo 2017-09-13 00:32:28 +08:00
In [538]: [elm + s[1::2][idx] for idx, elm in enumerate(s[::2])]
Out[538]: ['7w', '87', '65', '43', '21', '7w'] |
12
yucongo 2017-09-13 00:41:14 +08:00
In [544]: s
Out[544]: '7w876543217w' In [545]: [ s[2*idx: 2*idx+2] for idx in range(len(s)//2)] Out[545]: ['7w', '87', '65', '43', '21', '7w'] |