Ritz
Ritz

Reputation: 1253

How to split based on an alphabet?

I am trying to split based on an alphabet as below but somehow doesn't work,I have the current and expected output ,what am I doing wrong?how to fix it?

chiprev = ['4355b3','4364a1','4278b3']

for rev in chiprev:
    print rev.split("[a-b][A-B]")[-1]

CURRENT OUTPUT:-

4355b3
4364a1
4278b3

EXPECTED OUTPUT:-

b3
a1
b3

Upvotes: 2

Views: 773

Answers (3)

The fourth bird
The fourth bird

Reputation: 163642

You are trying to split using a regex on either ab or AB and therefore could use re.split

The regex that you use [a-b][A-B] will not give the expected output because it matches 2 ranges, a-b lowercase and A-B uppercase which does not find a match in your example data because it contains only a single a or b

If you are trying to split on a lower or uppercase alphabet a-z, you could make use of the flag re.IGNORECASE. As a regex, you could use a capturing group as the capturing group is returned.

([a-z][0-9]+)

That will match

  • ( Capturing group
    • [a-z] Match single character a-z
    • [0-9]+ Match 1+ times a digit (omit the + to match a single digit)
  • ) Close capturing group

From the result take the second field. For example:

import re
chiprev = ['4355b3','4364a1', '4278b3']
for rev in chiprev:
    print (re.split("([a-z][0-9]+)", rev, flags=re.IGNORECASE)[1])

Result

b3
a1
b3

Demo

Upvotes: 0

haxtar
haxtar

Reputation: 2070

This uses the search regular expression operation.

In words, it is essentially taking each rev, finding all sub-pieces that begin with a-b (downcased) or A-B (uppercase), hence the | operator. The + signifies to also extract whatever follows. This will allow the search to also extract the numbers that follow the letter.

chiprev = ['4355b3','4364a1','4278b3']

for rev in chiprev:
    print re.search(r'([a-b]|[A-B]).+',rev).group()

Output:

b3
a1
b3

Upvotes: 2

Naga kiran
Naga kiran

Reputation: 4607

for i in chiprev:
    print(i[re.search(r'[a-zA-Z]',i).start():])

Out:

b3
a1
b3

Upvotes: 2

Related Questions