1

I have a text line and i want to assign a variable to a certain string which appears directly after the symbol '@' in this line of text

09807754 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 @ 09623038 n 0000

The only thing is that this word may not appear in the same location so I can't just go like this

L = line.split()
K = L[-2]

It has to be searched as the first string after the '@' symbol. That is the only place it remains constant.

what i would like is for K = 09623038

4

4 回答 4

2

只是分裂@,然后分裂它之后的任何东西。

before_at, after_at = line.split('@')
K = int(after_at.split()[0])

为了提高效率,如果您只想要 , 之后的第一件事@-after_at.split(None, 1)只拆分一次(在空格上)。

当有多个 时,这将引发异常@,这可能是也可能不是您想要的。

于 2013-06-12T16:04:36.720 回答
1

分区是你的朋友:

>>> s='09807754 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 @ 09623038 n 0000'
>>> s.rpartition('@')
('09807754 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 ', '@', ' 09623038 n 0000')
>>> k=int(s.rpartition('@')[-1].split()[0])
>>> k
9623038
于 2013-06-12T17:17:07.673 回答
0

如果您更喜欢使用非正则表达式路线,这里有一个功能可以解决您的问题

def findVariable( s ):
    try:
        start = s.index( "@ " ) + 2
        end = s.index( " ", start )
        return s[start:end]
    except ValueError:
        return ""

print(findVariable("09807754 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 @ 09623038 n 0000"))

回报:09623038

于 2013-06-12T16:15:39.630 回答
0

使用regex

>>> import re
>>> strs = '09807754 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 @ 09623038 n 0000'
>>> re.search(r'@\s+([A-Za-z0-9]+)',strs).group(1)
'09623038'
于 2013-06-12T16:06:03.950 回答