每n個字符分割一個字符串?

本文翻譯自:Split string every nth character?

Is it possible to split a string every nth character? 是否可以每n個字符分割一個字符串?

For example, suppose I have a string containing the following: 例如,假設我有一個包含以下內容的字符串:

'1234567890'

How can I get it to look like this: 我怎樣才能使它看起來像這樣:

['12','34','56','78','90']

#1樓

參考:https://stackoom.com/question/dkwT/每n個字符分割一個字符串


#2樓

I like this solution: 我喜歡這個解決方案:

s = '1234567890'
o = []
while s:
    o.append(s[:2])
    s = s[2:]

#3樓

You could use the grouper() recipe from itertools : 您可以使用itertools grouper()配方:

Python 2.x: Python 2.x:

from itertools import izip_longest    

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Python 3.x: Python 3.x:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

These functions are memory-efficient and work with any iterables. 這些函數可節省內存,並且可與任何迭代程序一起使用。


#4樓

As always, for those who love one liners 一如既往,對於那些喜歡一隻班輪的人

n = 2  
line = "this is a line split into n characters"  
line = [line[i * n:i * n+n] for i,blah in enumerate(line[::n])]

#5樓

Spooky one – tried to invent yet another answer: 詭異的-嘗試發明另一個答案:

def split(s, chunk_size):
    a = zip(*[s[i::chunk_size] for i in range(chunk_size)])
    return [''.join(t) for t in a]

print(split('1234567890', 1))
print(split('1234567890', 2))
print(split('1234567890', 3))

Out

['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
['12', '34', '56', '78', '90']
['123', '456', '789']

#6樓

I've got this code that I use whenever I need to do this: 每當執行此操作時,我都會使用以下代碼:

def split_string(n, st):
    lst = [""]
    for i in str(st):
        l = len(lst) - 1
        if len(lst[l]) < n: 
            lst[l] += i
        else:
            lst += [i]
    return lst

print(split_string(3, "test_string."))

Where: 哪裏:

  • n is the length of each list item n是每個列表項的長度
  • st is the string to be split up st是要拆分的字符串
  • lst is the list version of st lstst的列表版本
  • i is the current character being used in st ist中使用的當前字符
  • l is the length of the last list item l是最後一個列表項的長度
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章