0

So I have a string

s = '>n269412 | AK142815 | msdfhakjfdkjfs'

and I want to include everything up to but not including the first instance of '|'

so what I did was

import re

p = re.search('|',s)

print s[:p]

but i got this error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method

I understand why it isn't working . . because that value is not an integer but is there any way I can use that value where the search found that element ?

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
O.rka
  • 29,847
  • 68
  • 194
  • 309

5 Answers5

5

Why even bother with a regex for this use-case?

s = '>n269412 | AK142815 | msdfhakjfdkjfs'
print s.partition('|')[0]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
3

You do not need regular expressions for this:

first, rest = s.split('|', 1)
Francis Avila
  • 31,233
  • 6
  • 58
  • 96
2

I think re.match() gives a more direct solution (i.e. match everything up to and not including the first |):

In [7]: re.match('[^|]*', s).group(0)
Out[7]: '>n269412 '

If there's no |, the entire string is returned. It is not entirely clear from the question whether this is what you want.

But as others have said, you don't really need a regex for this...

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

re.search returns a match object containing more that just a single index.

What you probably want is the start index:

>>> s[:p.start()]
'>n269412 '

Btw. you need to fix your regular expression as this would just match either '' or '' (i.e. nothing). You want to use '\|':

p = re.search('\|', s)
poke
  • 369,085
  • 72
  • 557
  • 602
0

That error is because re.search returns a MatchObject, which you attempt to slice and cannot do. See the re.search documentation.

I would do the following:

s = '>n269412 | AK142815 | msdfhakjfdkjfs'

# look for the pipe character
findPipe = s.find("|")

# replace everything after the pipe with empty string
s = s.replace(s[findPipe:], "")

print s

See these two links for more info about slicing strings.

Community
  • 1
  • 1
Murkantilism
  • 1,060
  • 1
  • 16
  • 31