我怎样才能拍摄像'aaaaaaaaaaaaaaaaaaaaaaa'
这样的字符串
并将其拆分为4个长度元组,如(aaaa
,aaaa
,aaaa
)
答案 0 :(得分:20)
>>> import textwrap
>>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
>>> textwrap.wrap(s, 4)
['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa']
答案 1 :(得分:12)
使用列表理解,生成器表达式:
>>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
>>> [s[i:i+4] for i in range(0, len(s), 4)]
['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa']
>>> tuple(s[i:i+4] for i in range(0, len(s), 4))
('aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa')
>>> s = 'a bcdefghi j'
>>> tuple(s[i:i+4] for i in range(0, len(s), 4))
('a bc', 'defg', 'hi j')
答案 2 :(得分:3)
使用正则表达式的另一种解决方案:
>>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
>>> import re
>>> re.findall('[a-z]{4}', s)
['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa']
>>>
答案 3 :(得分:2)
您可以使用grouper recipe,zip(*[iter(s)]*4)
:
In [113]: s = 'aaaaaaaaaaaaaaaaaaaaaaa'
In [114]: [''.join(item) for item in zip(*[iter(s)]*4)]
Out[114]: ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa']
请注意,如果字符串包含空格,textwrap.wrap
可能不会将s
拆分为长度为4的字符串:
In [43]: textwrap.wrap('I am a hat', 4)
Out[43]: ['I am', 'a', 'hat']
石斑鱼配方比使用textwrap
更快:
In [115]: import textwrap
In [116]: %timeit [''.join(item) for item in zip(*[iter(s)]*4)]
100000 loops, best of 3: 2.41 µs per loop
In [117]: %timeit textwrap.wrap(s, 4)
10000 loops, best of 3: 32.5 µs per loop
石斑鱼配方可以使用任何迭代器,而textwrap
仅适用于字符串。
答案 4 :(得分:0)
s = 'abcdef'
我们需要分成两部分
[s[pos:pos+2] for pos,i in enumerate(list(s)) if pos%2 == 0]
答案:
['ab', 'cd', 'ef']
答案 5 :(得分:0)
s = 'abcdefghi'
k-字符串的任何部分
k = 3
parts-列表以存储字符串的一部分
parts = [s[i:i+k] for i in range(0, len(s), k)]
parts-> ['abc','def','ghi']
答案 6 :(得分:0)
我认为这种方法更简单。但是消息长度必须用split_size分割。或必须在邮件中添加字母。例如:message =“ lorem ipsum_”,则可以删除添加的字母。
message = "lorem ipsum"
array = []
temp = ""
split_size = 3
for i in range(1, len(message) + 1):
temp += message[i - 1]
if i % split_size == 0:
array.append(temp)
temp = ""
print(array)
输出: ['lor','em','ips']
答案 7 :(得分:0)
这是给定问题的另一种可能的解决方案:
def split_by_length(text, width):
width = max(1, width)
chunk = ""
for v in text:
chunk += v
if len(chunk) == width:
yield chunk
chunk = ""
if chunk:
yield chunk
if __name__ == '__main__':
x = "123456789"
for i in range(20):
print(i, list(split_by_length(x, i)))
输出:
0 ['1', '2', '3', '4', '5', '6', '7', '8', '9']
1 ['1', '2', '3', '4', '5', '6', '7', '8', '9']
2 ['12', '34', '56', '78', '9']
3 ['123', '456', '789']
4 ['1234', '5678', '9']
5 ['12345', '6789']
6 ['123456', '789']
7 ['1234567', '89']
8 ['12345678', '9']
9 ['123456789']
10 ['123456789']
11 ['123456789']
12 ['123456789']
13 ['123456789']
14 ['123456789']
15 ['123456789']
16 ['123456789']
17 ['123456789']
18 ['123456789']
19 ['123456789']
答案 8 :(得分:0)
孩子的方式
def wrap(string, max_width):
i=0
strings = []
s = ""
for x in string:
i+=1
if i == max_width:
s = s + x
strings.append(s)
s = ""
i = 0
else:
s = s + x
strings.append(s)
return strings
wrap('ABCDEFGHIJKLIMNOQRSTUVWXYZ',4)
# output: ['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']