是否可以在python中拆分一个字符串并将每个部分拆分为一个变量以便以后使用?如果可能的话,我希望能够按长度进行拆分,但我不确定如何使用len().
我试过这个,但它没有得到我需要的东西:
x = 'this is a string'
x.split(' ', 1)
print x
Run Code Online (Sandbox Code Playgroud)
结果:['this']
我想结果是这样的:
a = 'this'
b = 'is'
c = 'a'
d = 'string'
Run Code Online (Sandbox Code Playgroud)
如果您想一次访问3个字符的字符串,则需要使用切片.
您可以使用如下列表理解来获取字符串的3个字符长片段的列表:
>>> x = 'this is a string'
>>> step = 3
>>> [x[i:i+step] for i in range(0, len(x), step)]
['thi', 's i', 's a', ' st', 'rin', 'g']
>>> step = 5
>>> [x[i:i+step] for i in range(0, len(x), step)]
['this ', 'is a ', 'strin', 'g']
Run Code Online (Sandbox Code Playgroud)
重要的是:
[x[i:i+step] for i in range(0, len(x), step)]
Run Code Online (Sandbox Code Playgroud)
range(0, len(x), step)获取每个step字符切片开头的索引. for i in将迭代这些指数. x[i:i+step]获取x从索引开始的切片,i并且step字符很长.
如果你知道你会得到确切每次四片,那么你可以这样做:
a, b, c, d = [x[i:i+step] for i in range(0, len(x), step)]
Run Code Online (Sandbox Code Playgroud)
如果发生这种情况3 * step < len(x) <= 4 * step.
如果你没有正好四个部分,那么Python将ValueError试图解压缩这个列表.因此,我认为这种技术非常脆弱,不会使用它.
你可以干脆做
x_pieces = [x[i:i+step] for i in range(0, len(x), step)]
Run Code Online (Sandbox Code Playgroud)
现在,您曾经访问过的地方a,您可以访问x_pieces[0].对于b,您可以使用x_pieces[1]等等.这可以让您更灵活.
几种选择
我通常不倾向于使用正则表达式,但是要将字符串组合起来,使用它并不是太糟糕:
>>> s = 'this is a string'
>>> re.findall('.{1,3}', s)
['thi', 's i', 's a', ' st', 'rin', 'g']
Run Code Online (Sandbox Code Playgroud)
而且矫枉过正
>>> t = StringIO(s)
>>> list(iter(lambda: t.read(3), ''))
['thi', 's i', 's a', ' st', 'rin', 'g']
Run Code Online (Sandbox Code Playgroud)