10

是否可以在 python 中拆分一个字符串并将每个拆分的部分分配给一个变量以供以后使用?如果可能的话,我希望能够按长度拆分,但我不确定使用 len() 将如何工作。

我试过了,但它没有得到我需要的东西:

x = 'this is a string'
x.split(' ', 1)
print x

结果:['这个']

我想得到这样的结果:

a = 'this'
b = 'is'
c = 'a'
d = 'string'
4

8 回答 8

11

如果您想一次访问 3 个字符的字符串,则需要使用slicing

您可以使用这样的列表推导获取字符串的 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']

重要的一点是:

[x[i:i+step] for i in range(0, len(x), step)]

range(0, len(x), step)为我们获取每个step-character 切片开始的索引。 for i in将遍历这些索引。 x[i:i+step]获取x从索引开始istep字符长的切片。

如果你知道你每次都会得到四件,那么你可以这样做

a, b, c, d = [x[i:i+step] for i in range(0, len(x), step)]

如果3 * step < len(x) <= 4 * step.

如果你没有正好四块,那么 Python 会给你一个ValueError尝试解压这个列表。因此,我认为这种技术非常脆弱,不会使用它。

你可以简单地做

x_pieces = [x[i:i+step] for i in range(0, len(x), step)]

现在,你以前访问的地方a,你可以访问x_pieces[0]。对于b, 你可以使用x_pieces[1]等等。这使您具有更大的灵活性。

于 2012-12-06T18:17:33.930 回答
6

您可以使用解包

a,b,c,d=x.split(' ');
于 2012-12-06T18:10:49.367 回答
5

几个选择

我通常不倾向于正则表达式,但要分块一个字符串,使用它还不错:

>>> s = 'this is a string'
>>> re.findall('.{1,3}', s)
['thi', 's i', 's a', ' st', 'rin', 'g']

而且矫枉过正

>>> t = StringIO(s)
>>> list(iter(lambda: t.read(3), ''))
['thi', 's i', 's a', ' st', 'rin', 'g']
于 2012-12-06T18:54:23.580 回答
4

你可以尝试这样的事情:

In [77]: x = 'this is a string'

In [78]: a,b,c,d=[[y] for y in x.split()]

In [79]: a
Out[79]: ['this']

In [80]: b
Out[80]: ['is']

In [81]: c
Out[81]: ['a']

In [82]: d
Out[82]: ['string']

使用itertools.islice()

In [144]: s = 'this is a string'

In [145]: lenn=len(s)//3 if len(s)%3==0 else (len(s)//3)+1

In [146]: it=iter(s)

In [147]: ["".join(islice(it,3)) for _ in range(lenn)]
Out[147]: ['thi', 's i', 's a', ' st', 'rin', 'g']
于 2012-12-06T18:03:20.600 回答
1
x = 'this is a string'
splitted = x.split()
count = 0
while count <= len(splitted) -1:
    print splitted[count]
    count = count + 1

这将在一行中打印每个部分...在这里您还可以查看如何使用len()

while 循环将打印每一行,直到计数器达到最大长度

于 2012-12-06T18:20:43.287 回答
1
x, i = 'this is a string', 0 #assigning two variables at once
while i <= len(x):
   y = x[i: i + 3]
   print y
   i += 3  #i = i + 3

这包括“空格”字符(“”)。

如果要保留每个数字,请将它们保存在列表中:

x, my_list, i = 'this is a string', [], 0
while i <= len(x):
   y = x[i : i + 3]
   my_list.append(y)
   i += 3
于 2012-12-06T18:28:07.637 回答
0
 def tst(sentence):
    print sentence
    bn=sentence.split(" ");
    i=0
    for i in range(0,len(bn)):
          a= bn[i]
          i=i+1
          print a

以这种方式测试它:

 if __name__ == '__main__':
      x="my name is good"
      tst(x)
于 2012-12-06T19:17:30.430 回答
0

这将在字符串少于 27 个单词的约束下产生您想要的精确输出。如果您用完表示块的键,您始终可以使用生成器。

x      = 'this is a string'
chunks = x.split(' ')
key    = 'a'
for chunk in chunks:
    print key + " = " + chunk
    key = chr(ord(key) + 1)
于 2013-11-14T12:28:07.553 回答