如何以5个字符的块读取字符串?

时间:2015-10-03 19:56:03

标签: python string

我的Python代码应该输出一个字符串除以5个字符的数组。我不明白这里的逻辑:

string = 'j3h1273172' # example
def getStringSplitBy(num=5, string):
     for i in range(len(string)):
         print string[i+num]

输出应为:

['j3h12','73172']

5 个答案:

答案 0 :(得分:2)

使用def strings(num,string): print [string[i*num:(i+1)*num] for i in range(len(string)/num)]

x.Properties["Uid"].Value

答案 1 :(得分:2)

你可以这样试试,

>>> [string[:5], string[5:]]
['j3h12', '73172']

功能:

>>> def get_string_split_by(num, string):
...   string_len = len(string)
...   items = []
...   for ix in range(0,string_len, num):
...     items.append(string[ix:ix+num])
...   return items

>>> get_string_split_by(5, 'j3h1273172')
['j3h12', '73172']
>>> get_string_split_by(5, 'j3h127317212345')
['j3h12', '73172', '12345']

答案 2 :(得分:2)

该函数中没有任何逻辑,因为它有语法错误,但是它没有按预期工作。你可以简单地使用:

def get_string_split_by(num, string):
    return string[:num], string[num:]

答案 3 :(得分:2)

我认为itertools为此任务提供recipe

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)

答案 4 :(得分:1)

您需要使用Python的string slicing来分割字符串。您发布的代码是抓取单个字符而不是字符集。

此代码将字符串分成几部分。此外,num应该是第二个,因为它是一个可选参数。

def getStringSplitBy(string, num=5):
    # Take the length of the string divided by num to figure out how many
    # slices you'll end up with
    for i in range(len(string)//num):
        # Slice the string in chuncks that are num long
        yield string[num*i:num*(i+1)] # Yield to make this an iterable

string = 'j3h1273172' # example
result = list(getStringSplitBy(string,5))
print(result) # prints ['j3h12', '73172']