有没有办法获取一个4*x字符长的字符串,并将其切成4个字符串,每个x字符长,不知道字符串的长度?
例如:
>>>x = "qwertyui"
>>>split(x, one, two, three, four)
>>>two
'er'
Run Code Online (Sandbox Code Playgroud)
Ale*_*der 76
>>> x = "qwertyui"
>>> chunks, chunk_size = len(x), len(x)/4
>>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
['qw', 'er', 'ty', 'ui']
Run Code Online (Sandbox Code Playgroud)
fnk*_*nkr 14
我尝试过Alexanders的回答但在Python3中遇到了这个错误:
TypeError: 'float' object cannot be interpreted as an integer
Run Code Online (Sandbox Code Playgroud)
这是因为Python3中的除法运算符返回了一个浮点数.这对我有用:
>>> x = "qwertyui"
>>> chunks, chunk_size = len(x), len(x)//4
>>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
['qw', 'er', 'ty', 'ui']
Run Code Online (Sandbox Code Playgroud)
请注意第//2行的末尾,以确保截断为整数.
Eth*_*ord 12
在分割字符串中每第 n 个字符?,“狼”给出了最简洁的答案:
>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']
Run Code Online (Sandbox Code Playgroud)
some_string="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
x=3
res=[some_string[y-x:y] for y in range(x, len(some_string)+x,x)]
print(res)
Run Code Online (Sandbox Code Playgroud)
会产生
['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX', 'YZ']
Run Code Online (Sandbox Code Playgroud)
使用textwrap模块:
import textwrap
def wrap(s, w):
return textwrap.fill(s, w)
Run Code Online (Sandbox Code Playgroud)
:return str:
灵感来自亚历山大的答案
def wrap(s, w):
return [s[i:i + w] for i in range(0, len(s), w)]
Run Code Online (Sandbox Code Playgroud)
import re
def wrap(s, w):
sre = re.compile(rf'(.{{{w}}})')
return [x for x in re.split(sre, s) if x]
Run Code Online (Sandbox Code Playgroud)
小智 7
def split2len(s, n):
def _f(s, n):
while s:
yield s[:n]
s = s[n:]
return list(_f(s, n))
Run Code Online (Sandbox Code Playgroud)
小智 5
这是一个不需要事先知道字符串长度的单行:
from functools import partial
from StringIO import StringIO
[l for l in iter(partial(StringIO(data).read, 4), '')]
Run Code Online (Sandbox Code Playgroud)
如果您有文件或套接字,则不需要 StringIO 包装器:
[l for l in iter(partial(file_like_object.read, 4), '')]
Run Code Online (Sandbox Code Playgroud)