0

私はこのコードを持っていますが、機能していません

import re
mystring = "This is my test the string to match the stuff"    
p = re.compile(" the ")

var1で見つかった最初の一致と2番目の一致を入れたいvar2

4

1 に答える 1

4

このような意味ですか?

In [3]: import re

In [4]: strs= "This is my test the string to match the stuff"

In [5]: p = re.compile(" the ")

In [6]: re.findall(p,strs)
Out[6]: [' the ', ' the ']

In [7]: var1,var2=re.findall(p,strs)

In [8]: var1,var2
Out[8]: (' the ', ' the ')

返される一致の数が2を超える場合は、最初にリストをスライスします。

var1,var2=[' the ', ' the ',' the '][:2]

Python 3.xでは、を利用*してリスト内の残りの要素を取得できます。

In [2]: var1,var2,*extras=[' the ', ' the ','foo','bar']

In [3]: var1
Out[3]: ' the '

In [4]: var2
Out[4]: ' the '

In [5]: extras             #rest of the elements are stored in extras
Out[5]: ['foo', 'bar']
于 2013-01-22T03:22:16.697 に答える