有沒有辦法取一個長度爲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']
設置「塊」的價值是什麼?它始終是'len(x)' – Nitay
我試着回答亞歷山大,但得到這個錯誤在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行的目的,確保截斷爲整數。
這裏是一個班輪這並不需要知道字符串的長度事先:
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), '')]
如果您正在使用python3,則StringIO現在位於io模塊中。 –
而對於誰喜歡它有點更具可讀性帥哥:
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']
我的解決方案
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']
這裏有兩個通用的方法。可能值得添加到您自己的可重複使用庫中。第一個需要項目是可分片的,第二個需要與任何迭代器一起工作(但要求他們的構造函數接受迭代)。
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']
字符串分割,用替換字符另一個字符等等。但是所有這些操作都可以用下面提到的字符串分割方法來執行。
字符串分割可以通過兩種方式來完成:
切片基於分裂的長度給定的字符串。
將給定的字符串轉換爲具有list(str)函數的列表,其中字符串的字符分解以形成列表的元素。然後執行所需的操作並將它們與'原始字符串'的字符之間的指定字符'加入(列表)以獲得新的處理過的字符串。
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)
儘管這段代碼可能會解決這個問題,[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高您的質量帖子。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! – kayess
有一個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']
然後是FUNC,它可能是這樣的:
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]
使用textwrap模塊:
import textwrap
def wrap(s, w):
return textwrap.fill(s, w)
:返回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]
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 )]
嗨Frederico,歡迎來到SO!解釋爲什麼你在這個答案中做了你所做的事情可能是值得的,這樣你顯示的語言和想法的新手就能理解爲什麼這是一個好的行動方案。 –
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']
你就不能索要字符串的長度與' LEN(X)'? – Eric
Eric:那你怎麼能用這個? – tkbx
切片符號? –