2

I have the following string

myString = "cat(50),dog(60),pig(70)"

I try to convert the above string to 2D array. The result I want to get is

myResult = [['cat', 50], ['dog', 60], ['pig', 70]]

I already know the way to solve by using the legacy string method but it is quite complicated. So I don't want to use this approach.

# Legacy approach
# 1. Split string by ","
# 2. Run loop and split string by "(" => got the <name of animal>
# 3. Got the number by exclude ")".

Any suggestion would appreciate.

2 Answers 2

6

You can use the re.findall method:

>>> import re
>>> re.findall(r'(\w+)\((\d+)\)', myString)
[('cat', '50'), ('dog', '60'), ('pig', '70')]

If you want a list of lists as noticed by RomanPerekhrest convert it with a list comprehension:

>>> [list(t) for t in re.findall(r'(\w+)\((\d+)\)', myString)]
[['cat', '50'], ['dog', '60'], ['pig', '70']]
Sign up to request clarification or add additional context in comments.

1 Comment

should be [list(t) for t in re.findall(r'(\w+)\((\d+)\)', myString)]
2

Alternative solution using re.split() function:

import re
myString = "cat(50),dog(60),pig(70)"
result = [re.split(r'[)(]', i)[:-1] for i in myString.split(',')]

print(result)

The output:

[['cat', '50'], ['dog', '60'], ['pig', '70']]

r'[)(]' - pattern, treats parentheses as delimiters for splitting

[:-1] - slice containing all items except the last one(which is empty space ' ')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.