Reputation: 135
So I have the next list:
a = ["[Test](Link)", "[Test2](link2)", "[test3](link3)"]
And I want to get it to show in this way:
b1 = Test
b2 = Link
b3 = test3
b4 = link2
b5 = test3
b6 = link3
How could I do something like this?
I've tried to join the list and use re to get what I want but I failed
Upvotes: 0
Views: 58
Reputation: 12015
>>> a = ["[Test](Link)", "[Test2](link2)", "[test3](link3)"]
>>> b1,b2,b3,b4,b5,b6 = (y.strip('[]()') for x in a for y in x.split(']'))
>>> print (b1,b2,b3,b4,b5,b6)
Test Link Test2 link2 test3 link3
Upvotes: 0
Reputation: 1439
Your original question looks like you want each value to be representing by a new variable. You can use globals()
to dynamically create new variables.
count = 0
g = globals()
for i in a:
f = i.strip('[)').split('](')
count += 1
g['b' + str(count)] = f[0]
print ('b' + str(count) + ' = ' + f[0])
count += 1
g['b' + str(count)] = f[1]
print ('b' + str(count) + ' = ' + f[1])
b1 = Test
b2 = Link
b3 = Test2
b4 = link2
b5 = test3
b6 = link3
Below is the output of the variables that were dynamically created.
In [5]: b1
Out[5]: 'Test'
In [6]: b2
Out[6]: 'Link'
In [7]: b3
Out[7]: 'Test2'
In [8]: b4
Out[8]: 'link2'
In [9]: b5
Out[9]: 'test3'
In [10]: b6
Out[10]: 'link3'
Upvotes: 0
Reputation: 51165
You can use re.findall
after using join
on your list:
>>> re.findall(r'(\[.*?\]|\(.*?\))', ''.join(a))
['[Test]', '(Link)', '[Test2]', '(link2)', '[test3]', '(link3)']
Regex Explanation:
( # Matching group 1
\[.*?\] # Matches non-greedily in between brackets
| # OR
\(.*?\) # Matches non-greedily between parenthesis
) # End of matching group
Upvotes: 1
Reputation: 223052
import re
a = ["[Test](Link)", "[Test2](link2)", "[test3](link3)"]
for s in a:
m = re.match('(\[.*\])(\(.*\))$', s)
print(m.group(1))
print(m.group(2))
results:
[Test]
(Link)
[Test2]
(link2)
[test3]
(link3)
Upvotes: 1