有没有办法获取长度为4*x
个字符的字符串,并将其剪切成4个字符串,每个x
个字符长,而不知道字符串的长度?
例如:
>>>x = "qwertyui"
>>>split(x, one, two, three, four)
>>>two
'er'
答案 0 :(得分:69)
>>> 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']
答案 1 :(得分:14)
我尝试过Alexanders的回答,但在Python3中遇到了这个错误:
TypeError: 'float' object cannot be interpreted as an integer
这是因为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行末尾的//
,以确保截断为整数。
答案 2 :(得分:7)
使用textwrap模块:
import textwrap
def wrap(s, w):
return textwrap.fill(s, w)
:return str:
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]
答案 3 :(得分:4)
这是一个单行,不需要事先知道字符串的长度:
from functools import partial
from StringIO import StringIO
[l for l in iter(partial(StringIO(data).read, 4), '')]
如果您有文件或套接字,那么您不需要StringIO包装器:
[l for l in iter(partial(file_like_object.read, 4), '')]
答案 4 :(得分:3)
def split2len(s, n):
def _f(s, n):
while s:
yield s[:n]
s = s[n:]
return list(_f(s, n))
答案 5 :(得分:1)
以下是两种通用方法。可能值得添加到您自己的可重用的库中。第一个要求项是可切片的,第二个要求任何迭代(但要求它们的构造函数接受迭代)。
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
因此,在topicstarter的案例中,用法是:
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']
答案 6 :(得分:1)
得到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]
答案 7 :(得分:1)
length = 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 )]
答案 8 :(得分:1)
some_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']
答案 9 :(得分:1)
在Split string every nth character?中,“狼”给出了最简洁的答案:
>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']
答案 10 :(得分:0)
对于那些喜欢它更具可读性的家伙来说:
def itersplit_into_x_chunks(string,x=10): # we assume here that x is an int and > 0
size = len(string)
chunksize = size//x
for pos in range(0, size, chunksize):
yield string[pos:pos+chunksize]
输出:
>>> list(itersplit_into_x_chunks('qwertyui',x=4))
['qw', 'er', 'ty', 'ui']
答案 11 :(得分:0)
在许多情况下需要进行字符串拆分,例如必须对给定字符串的字符进行排序,用另一个字符替换字符等。但是所有这些操作都可以使用以下提到的字符串拆分方法执行。
字符串拆分可以通过两种方式完成:
根据拆分的长度切片给定的字符串。
将给定字符串转换为带有list(str)函数的列表,其中字符串的字符细分以形成列表的元素。然后执行所需的操作并使用'原始字符串'.join(list)的字符之间的“指定字符”将它们连接起来以获取新处理的字符串。
答案 12 :(得分:0)
# spliting a string by the length of the string
def len_split(string,sub_string):
n,sub,str1=list(string),len(sub_string),')/^0*/-'
for i in range(sub,len(n)+((len(n)-1)//sub),sub+1):
n.insert(i,str1)
n="".join(n)
n=n.split(str1)
return n
x="divyansh_looking_for_intership_actively_contact_Me_here"
sub="four"
print(len_split(x,sub))
# Result-> ['divy', 'ansh', 'tiwa', 'ri_l', 'ooki', 'ng_f', 'or_i', 'nter', 'ship', '_con', 'tact', '_Me_', 'here']
答案 13 :(得分:-1)
l = 'abcdefghijklmn'
def group(l,n):
tmp = len(l)%n
zipped = zip(*[iter(l)]*n)
return zipped if tmp == 0 else zipped+[tuple(l[-tmp:])]
print group(l,3)
答案 14 :(得分:-2)
我的解决方案
st =' abs de fdgh 1234 556 shg shshh'
print st
def splitStringMax( si, limit):
ls = si.split()
lo=[]
st=''
ln=len(ls)
if ln==1:
return [si]
i=0
for l in ls:
st+=l
i+=1
if i <ln:
lk=len(ls[i])
if (len(st))+1+lk < limit:
st+=' '
continue
lo.append(st);st=''
return lo
############################
print splitStringMax(st,7)
# ['abs de', 'fdgh', '1234', '556', 'shg', 'shshh']
print splitStringMax(st,12)
# ['abs de fdgh', '1234 556', 'shg shshh']