0

How can i get a string after a special character?

For example I want to get the string after / in

my_string = "Python/RegEx"

Output to be : RegEx

I tried :

h = []
a = [ 'Python1/RegEx1' , 'Python2/RegEx2', 'Python3/RegEx3']

for i in a: 
    h.append(re.findall(r'/(\w+)', i))
print(h)

But the output is : [['RegEx1'], ['RegEx2'], ['RegEx3']]

I need : ['RegEx1', 'RegEx2', 'RegEx3']

Thanks in advance

RegEx beginner

Ebin Davis
  • 5,421
  • 3
  • 15
  • 20

4 Answers4

0

Loop through the list of lists you get with another for loop.

For example:

a = [ 'Python1/RegEx1' , 'Python2/RegEx2', 'Python3/RegEx3']

for i in a: 
    h.append(re.findall(r'/(\w+)', i))

for x in h:
    print(x)
ech0
  • 512
  • 4
  • 14
0

For something like this where you only have one / per item, you could use map to .split('/') each item and then take .split('/')[1] from each item to create the list

a = [ 'Python1/RegEx1' , 'Python2/RegEx2', 'Python3/RegEx3']
a = list(map(lambda x: x.split('/')[1], a))
# ['RegEx1', 'RegEx2', 'RegEx3']

Or list comprehension

a = [i.split('/')[1] for i in a]

Expanded :

l = []
for i in a:
    i = i.split('/')
    l.append(i[1])
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
0

You may use [0] in front of findall:

>>> h = []
>>> for i in a:
...     res = re.findall(r'/(\w+)', i)
...     if res:
...           h.append(res[0])
...
>>> print (h)
['RegEx1', 'RegEx2', 'RegEx3']
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Using .extend():

for i in a: 
    h.extend(re.findall(r'/(\w+)', i))

Using += (just another way to call .extend):

for i in a: 
    h += re.findall(r'/(\w+)', i)

Using unpacking:

for i in a: 
    h.append(*re.findall(r'/(\w+)', i))
jedwards
  • 29,432
  • 3
  • 65
  • 92