有没有一种方法可以将一个长度为4*x
的字符串切成4个长度为x
个字符的子串,而不需要知道字符串的长度?
例如:
>>>x = "qwertyui"
>>>split(x, one, two, three, four)
>>>two
'er'
有没有一种方法可以将一个长度为4*x
的字符串切成4个长度为x
个字符的子串,而不需要知道字符串的长度?
例如:
>>>x = "qwertyui"
>>>split(x, one, two, three, four)
>>>two
'er'
>>> 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']
chunks
的价值是什么?它将始终为 x
的长度。 - Nitaylen(x)
称为“chunks”并不支持这个目标。 “chunks”的名称是“块数”,对吧?所以它应该设置为4。如果你想给len(x)
命名,就把它命名为“length”。 - MarredCheese使用textwrap模块:
import textwrap
def wrap(s, w):
return textwrap.fill(s, w)
def wrap(s, w):
return [s[i:i + w] for i in range(0, len(s), w)]
import re
def wrap(s, w):
sre = re.compile(rf'(.{{{w}}})')
return [x for x in re.split(sre, s) if x]
我尝试了Alexanders的答案,但在Python3中遇到了这个错误:
TypeError:'float'对象无法解释为整数
这是因为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']
注意第2行末尾的//
,以确保截断为整数。
//
来代替强制转换为整数:len(x)//4
。此外,我认为在int(len(x))
中的强制转换是不必要的。 - BoppreHsome_string="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
x=3
res=[some_string[y-x:y] for y in range(x, len(some_string)+x,x)]
print(res)
将产生
['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX', 'YZ']
在如何将字符串每隔n个字符拆分一次?问题中,“the wolf”给出了最简洁的答案:
>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']
def split2len(s, n):
def _f(s, n):
while s:
yield s[:n]
s = s[n:]
return list(_f(s, n))
from functools import partial
from StringIO import StringIO
[l for l in iter(partial(StringIO(data).read, 4), '')]
[l for l in iter(partial(file_like_object.read, 4), '')]
学会了一个有关re
的技巧:
In [28]: import re
In [29]: x = "qwertyui"
In [30]: [x for x in re.split(r'(\w{2})', x) if x]
Out[30]: ['qw', 'er', 'ty', 'ui']
def split(string, split_len):
# Regex: `r'.{1}'` for example works for all characters
regex = r'(.{%s})' % split_len
return [x for x in re.split(regex, string) if x]
list(filter(None, re.split(r'(\w{2})', x)))
- Billre.findall(r'(\w{2})', x)
。 - Billlength = 4
string = "abcdefgh"
str_dict = [ o for o in string ]
parts = [ ''.join( str_dict[ (j * length) : ( ( j + 1 ) * length ) ] ) for j in xrange(len(string)/length )]
def split_bylen(item, maxlen):
'''
Requires item to be sliceable (with __getitem__ defined)
'''
return [item[ind:ind+maxlen] for ind in range(0, len(item), maxlen)]
#You could also replace outer [ ] brackets with ( ) to use as generator.
def split_bylen_any(item, maxlen, constructor=None):
'''
Works with any iterables.
Requires item's constructor to accept iterable or alternatively
constructor argument could be provided (otherwise use item's class)
'''
if constructor is None: constructor = item.__class__
return [constructor(part) for part in zip(* ([iter(item)] * maxlen))]
#OR: return map(constructor, zip(* ([iter(item)] * maxlen)))
# which would be faster if you need an iterable, not list
。
string = 'Baboons love bananas'
parts = 5
splitlen = -(-len(string) // parts) # is alternative to math.ceil(len/parts)
first_method = split_bylen(string, splitlen)
#Result :['Babo', 'ons ', 'love', ' ban', 'anas']
second_method = split_bylen_any(string, splitlen, constructor=''.join)
#Result :['Babo', 'ons ', 'love', ' ban', 'anas']
len(x)
来获取字符串的长度吗? - Eric